在圣人中,对未知函数f(x)进行泰勒展开是相当容易的,
x = var('x')
h = var('h')
f = function('f',x)
g1 = taylor(f,x,h,2)
Run Code Online (Sandbox Code Playgroud)
如何在同情中做到这一点?
更新
asmeurer指出,这是一个很快就可以通过拉动请求http://github.com/sympy/sympy/pull/1888获得的功能.我用pip安装了分支,
pip install -e git+git@github.com:renatocoutinho/sympy.git@897b#egg=sympy --upgrade
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试计算f(x)的系列时,
x, h = symbols("x,h")
f = Function("f")
series(f,x,x+h)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误,
TypeError:必须使用f实例作为第一个参数调用未绑定方法series()(改为使用Symbol实例)
Løi*_*ten 11
正如@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))
Run Code Online (Sandbox Code Playgroud)
要么
from sympy import series
pprint(series(f(x), x, x0=h, n=3))
Run Code Online (Sandbox Code Playgroud)
两者都回归
? 2 ??
2 ? d ??
(-h + x) ??????(f(??))??
? 2 ??
? d ?? ?d?? ????=h ? 3 ?
f(h) + (-h + x)?????(f(??))?? + ???????????????????????????? + O?(-h + x) ; x ? h?
?d?? ????=h 2
Run Code Online (Sandbox Code Playgroud)
如果你想要一个有限差分近似,你可以写例如
FW = f(x+h).series(x+h, x0=x0, n=3)
FW = FW.subs(x-x0,0)
pprint(FW)
Run Code Online (Sandbox Code Playgroud)
获得前向近似值,返回值
? 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
Run Code Online (Sandbox Code Playgroud)
在同情中没有这个功能,但是"手动"这样做很容易:
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)
Run Code Online (Sandbox Code Playgroud)
请注意,sympy通常适用于表达式(如f(x)),而不适用于裸函数(如f).