How to do a symbolic taylor expansion of an unknown function $f(x)$ using sympy

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) 

How can this be done in sympy?


Update

asmeurer points out that this is a feature which will be available soon in sympy from the pull request . I installed the branch using pip,

pip install -e [email protected]:renatocoutinho/sympy.git@897b#egg=sympy --upgrade 

However, when I try to calculate the series of f(x),

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

I get the following error,

TypeError: unbound method series() must be called with f instance as first argument (got Symbol instance instead)

11

2 Answers

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)) 

or

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

both returns

 ⎛ 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) 

to get the forward approximation, which returns

 ⎛ 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 

There is no function for this in sympy, but it's rather easy to do it "by hand":

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) 

Note that sympy typically works with expressions (like f(x)) and not with bare functions (like f).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like