Anyway, I was browsing Kline's section on Taylor Series last night and it made me think of a little project. Before I get to that, if you don't know, the Taylor Series for sin(x), cos(x) and ex can be used to derive Euler's famous formula, which we touched on briefly a while back (here and here).
The project: there is a terrific graphic in the wikipedia article showing what a good approximation one can get with only a few terms from the series. So that's our goal for today, to reproduce the plot using matplotlib.
The Taylor series for f(x) when x is near a:
fnis the nth derivative of f
If a = 0 this is the Maclaurin series
For sin(0) and cos(0) the sequential derivatives form a repeating series (with period equal to 4) and every other term equal to 0. If f(x) is sin(x):
All the sin(0) terms are equal to 0, and cos(0) is equal to 1:
To make the plot, we define a "factory" function that returns functions for the various degrees:
which we will call with odd values of n. Then the only trick to the plot is to accumulate the sum. We plot the sine curve last so that it lies on top of the others. Sure enough, with 8 terms we can cover roughly -2π < x < 2π.