""" The purpose of this exercise is to animate how the accuracy of a Taylor series approximation improves as we include more terms in the series. The recipe used is the same as in 'animate_gauss1.py' """ import numpy as np from math import factorial import matplotlib.pyplot as plt """ Define a function to create the animation. The function takes a function fk as argument, which is the function that defines each term in the taylor series. See the book for an explanation of the other arguments. """ def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin,xmax,n) s = np.zeros(n) #set the axis and create the object 'lines' plt.axis([xmin,xmax,ymin,ymax]) plt.plot(x,exact(x)) lines = plt.plot(x,s) for k in range(M,N+1): s = s + fk(x,k) lines[0].set_ydata(s) plt.draw() plt.pause(0.2) #a single term in the Taylor series for sin(x), as a function of k and x: def fk_sin(x,k): return (-1)**k*x**(2*k+1)/factorial(2*k+1) #Taylor series term for exp(-x): def fk_expinv(x,k): return (-x)**k/factorial(k) def expinv(x): return np.exp(-x) #call the function to animate the two series: animate_series(fk_sin,0,40,0,13*np.pi,-2,2,200,np.sin) #animate_series(fk_expinv,0,30,0,15,-0.5,1.4,200,expinv)