12

セージでは、未知の関数f(x)のテイラー展開を行うのはかなり簡単です。

x = var('x')
h = var('h')
f = function('f',x)
g1 = taylor(f,x,h,2)

これはsympyでどのように行うことができますか?


アップデート

asmeurer は、これがプル リクエストhttp://github.com/sympy/sympy/pull/1888から sympy ですぐに利用できる機能であると指摘しています。pipを使用してブランチをインストールしましたが、

pip install -e git+git@github.com:renatocoutinho/sympy.git@897b#egg=sympy --upgrade

しかし、f(x)の級数を計算しようとすると、

x, h = symbols("x,h")
f = Function("f")
series(f,x,x+h)

次のエラーが表示されます。

TypeError: unbound メソッド series() は、最初の引数として f インスタンスを使用して呼び出す必要があります (代わりに Symbol インスタンスを取得しました)

4

2 に答える 2

16

@asmeurerが説明したように、これは現在可能です

from sympy import init_printing, symbols, Function
init_printing()

x, h = symbols("x,h")
f = Function("f")

pprint(f(x).series(x, x0=h, n=3))

また

from sympy import series
pprint(series(f(x), x, x0=h, n=3))

両方のリターン

                                              ⎛  2        ⎞│                          
                                            2 ⎜ d         ⎟│                          
                                    (-h + x) ⋅⎜────(f(ξ₁))⎟│                          
                                              ⎜   2       ⎟│                          
                ⎛ d        ⎞│                 ⎝dξ₁        ⎠│ξ₁=h    ⎛        3       ⎞
f(h) + (-h + x)⋅⎜───(f(ξ₁))⎟│     + ──────────────────────────── + O⎝(-h + x) ; x → h⎠
                ⎝dξ₁       ⎠│ξ₁=h                2                                    

有限差分近似が必要な場合は、たとえば次のように書くことができます

FW = f(x+h).series(x+h, x0=x0, n=3)
FW = FW.subs(x-x0,0)
pprint(FW)

を返す前方近似を取得します。

                                  ⎛  2        ⎞│
                                2 ⎜ d         ⎟│
                               h ⋅⎜────(f(ξ₁))⎟│
                                  ⎜   2       ⎟│
          ⎛ d        ⎞│           ⎝dξ₁        ⎠│ξ₁=x₀    ⎛ 3    2        2    3                 ⎞
f(x₀) + h⋅⎜───(f(ξ₁))⎟│      + ────────────────────── + O⎝h  + h ⋅x + h⋅x  + x ; (h, x) → (0, 0)⎠
          ⎝dξ₁       ⎠│ξ₁=x₀             2
于 2016-04-01T07:14:34.690 に答える
8

sympy にはこの機能はありませんが、「手動で」実行するのはかなり簡単です。

In [3]: from sympy import *
        x, h = symbols('x, h')
        f = Function('f')
        sum(h**i/factorial(i) * f(x).diff(x, i) for i in range(4))

Out[3]: h**3*Derivative(f(x), x, x, x)/6 + h**2*Derivative(f(x), x, x)/2 + h*Derivative(f(x), x) + f(x)

sympy は通常、式 ( などf(x)) で動作し、裸の関数 ( などf) では動作しないことに注意してください。

于 2013-06-08T01:16:12.913 に答える