# How to compute the Taylor series for a function (in Python, using SymPy)

See all solutions.

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?

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


$\displaystyle e^{2 x + 1}$

Let’s ask for a degree-5 Taylor series centered at $x=2$. From the code below, you can tell that the third parameter is the center point and the fourth parameter is the degree.

1
series( formula, x, 2, 5 )


$\displaystyle e^{5} + 2 \left(x - 2\right) e^{5} + 2 \left(x - 2\right)^{2} e^{5} + \frac{4 \left(x - 2\right)^{3} e^{5}}{3} + \frac{2 \left(x - 2\right)^{4} e^{5}}{3} + O\left(\left(x - 2\right)^{5}; x\rightarrow 2\right)$

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


$\displaystyle \frac{2 \left(x - 2\right)^{4} e^{5}}{3} + \frac{4 \left(x - 2\right)^{3} e^{5}}{3} + 2 \left(x - 2\right)^{2} e^{5} + 2 \left(x - 2\right) e^{5} + e^{5}$

You can also compute individual coefficients in a Taylor series by remembering the formula for the $n^\text{th}$ term in the series and applying it, as follows. The formula for a series centered on $x=a$ is $\frac{f^{(n)}(a)}{n!}$.

From the answer above, we can see that the coefficient on the $n=3$ term is $\frac43e^5$.

1
2
3
n = 3
a = 2
diff( formula, x, n ).subs( x, a ) / factorial( n )


$\displaystyle \frac{4 e^{5}}{3}$