How to compute the Taylor series for a function (in Python, using SymPy)
Task
Any function that has arbitrarily many derivatives at a given point can have a Taylor series computed for the function centered at that point. How can we ask symbolic mathematics software to do this for us?
Related tasks:
Solution
This answer assumes you have imported SymPy as follows.
1
2
from sympy import * # load all math functions
init_printing( use_latex='mathjax' ) # use pretty math output
Let’s define an example function whose Taylor series we’d like to compute.
1
2
3
var( 'x' )
formula = exp( 2*x + 1 )
formula
Let’s ask for a degree-5 Taylor series centered at
1
series( formula, x, 2, 5 )
The final term (starting with O—oh, not zero) means that there are more terms in the infinite Taylor series not shown in this finite approximation. If you want to show just the approximation, you can tell it to remove the O term.
1
series( formula, x, 2, 5 ).removeO()
You can also compute individual coefficients in a Taylor series
by remembering the formula for the
From the answer above, we can see that the coefficient on the
1
2
3
n = 3
a = 2
diff( formula, x, n ).subs( x, a ) / factorial( n )
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)