nicoguaro
nicoguaro

Reputation: 3871

SymPy Taylor expansion for functions symbols

How can you perform a Taylor expansion with respect to function symbols in SymPy?

For example

from sympy import *
ode = f(x).diff(x, 2) - sin(f(x))

We would like to linearize the differential equation by doing something like

ode.series(f, 0, 1)

to obtain something like

f(x).diff(x, 2) - f(x)

But I can't figure it out how to do this in SymPy. In Maxima, I could define a dependency like

depends(y, x);
ode: diff(y, x, 2) - sin(y);
taylor(ode, y, 0, 8);

and it would result in

'diff(y,x,2) - y + y^3/6 - y^5/120 + y^7/5040 + ...

This could be really useful to linearize non-linear differential equations or in perturbation theory.

Upvotes: 4

Views: 2016

Answers (1)

user6655984
user6655984

Reputation:

You can temporarily replace f(x) by a symbol such as y, perform expansion with respect to that symbol, and then substitute back. Here is a self-contained example:

from sympy import *
var('x y')
f = Function('f')
ode = f(x).diff(x, 2) - sin(f(x))
ode_linear = series(ode.subs(f(x), y), y, 0, 2).removeO().subs(y, f(x))
ode_cubic = series(ode.subs(f(x), y), y, 0, 4).removeO().subs(y, f(x))

As a result, ode_linear is -f(x) + Derivative(f(x), x, x) and ode_cubic is f(x)**3/6 - f(x) + Derivative(f(x), x, x)

Upvotes: 4

Related Questions