如何使用 sympy 对未知函数 $f(x)$ 进行符号泰勒展开 [英] How to do a symbolic taylor expansion of an unknown function $f(x)$ using sympy
问题描述
在sage中,对未知函数进行泰勒展开是相当容易的f(x),
In sage it is fairly easy to do a Taylor expansion of an unknown function f(x),
x = var('x')
h = var('h')
f = function('f',x)
g1 = taylor(f,x,h,2)
如何在 sympy 中做到这一点?
How can this be done in sympy?
更新
asmeurer 指出,这是一个很快就会在 sympy 中从拉取请求中提供的功能 http://github.com/sympy/sympy/pull/1888.我使用 pip 安装了分支,
asmeurer points out that this is a feature which will be available soon in sympy from the pull request http://github.com/sympy/sympy/pull/1888. I installed the branch using pip,
pip install -e git+git@github.com:renatocoutinho/sympy.git@897b#egg=sympy --upgrade
然而,当我尝试计算f(x)的级数时,
However, when I try to calculate the series of f(x),
x, h = symbols("x,h")
f = Function("f")
series(f,x,x+h)
我收到以下错误,
TypeError: unbound method series() must be called with f instance as第一个参数(取而代之的是 Symbol 实例)
TypeError: unbound method series() must be called with f instance as first argument (got Symbol instance instead)
推荐答案
正如@asmeurer 所描述的,现在可以使用
As @asmeurer described, this is now possible with
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
如果你想要一个有限差分近似,你可以例如写
If you want a finite difference approximation, you can for example write
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
这篇关于如何使用 sympy 对未知函数 $f(x)$ 进行符号泰勒展开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!