""" Ex. 5.39 from "A primer on... Animate how a Taylor series approximation becomes increasingly accurate as we include more terms. The approach used here follows Recipe 1 for creating the animation. """ import numpy as np import matplotlib.pyplot as plt #factorial is not in numpy, need import from math: from math import factorial #a) Create the function: def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin, xmax, n) y_exact = exact(x) y = np.zeros_like(x) plt.axis([xmin, xmax, ymin, ymax]) plt.plot(x, y_exact) lines = plt.plot(x, y) for k in range(M, N+1): y = y + fk(x, k) lines[0].set_ydata(y) plt.draw() plt.pause(0.25) #b) Call the function for the Taylor series approximation to sin(x) def f_sin(x, k): return (-1)**k * x**(2 * k + 1) / factorial(2 * k + 1) animate_series(f_sin,M=0, N=40, xmin=0, xmax=13*np.pi, ymin=-2, ymax=2, n=100, exact = np.sin) #c) Call the function for the Taylor series approximation to exp(-x) def f_expinv(x, k): return (-x)**k / factorial(k) def exp_inv(x): return np.exp(-x) animate_series(f_expinv, 0, 30, 0, 15, -0.5, 1.4, 100, exp_inv)