""" Exercise 5.39 from "A Primer on..." Fairly advanced plotting exercise, where the task is to visualize the evolution of a Taylor series approximation as we add more terms. The details of creating the actual animation are not important to remember (and there will not be animation questions on the exam), but the overall exercise is a useful repetition of many topics, including function programming, array computing, plotting etc. """ import numpy as np import matplotlib.pyplot as plt from math import factorial #a) create the function that does the animation def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin, xmax, n) s = np.zeros_like(x) 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_data(x, s) plt.draw() plt.pause(0.3) #b) call the function to animate the Taylor series for the sine function def fk_sin(x, k): return (-1)**k * x**(2 * k +1) / factorial(2 * k + 1) animate_series(fk_sin, 0, 40, 0, 13 * np.pi, -2, 2, 201, np.sin) #clear the figure to be ready for next animation: plt.cla() #b) call the function again, now to animate the inverse exponential: def f_exp_inv(x, k): return (-x)**k / factorial(k) def exp_inv(x): return np.exp(-x) animate_series(f_exp_inv, 0, 30, 0, 15, -0.5, 1.4, 201, exp_inv)