""" Ex. 5.39 from "A primer on..." Make a function that computes and animates a series (for instance a Taylor series) as more and more terms are included. """ import numpy as np import matplotlib.pyplot as plt from math import factorial def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin, xmax, n) s = np.zeros_like(x) #fix the axes of the plot (important for animations): plt.axis([xmin, xmax, ymin, ymax]) #plot the exact function: plt.plot(x,exact(x)) #keep the plot object in a variable to update it later: 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.3) #b) use the function to approximate sin(x): def fk_sin(x, k): return (-1)**k * x**(2 * k + 1) / factorial(2 * k + 1) """ Note the first and last arguments in the function call below. The first is the function specifying each term in the series, which we defined above. The last (exact) is the function we want to approximate. Both functions are passed as arguments and used inside animate_series. The remaining arguments are numbers, as specified in the question text. """ animate_series(fk_sin, M = 0, N = 40, xmin = 0, xmax = 13 * np.pi, ymin = -2, ymax = 2, n = 200, exact = np.sin) #clear the previous plot, to get ready for next plt.clf() #c) approximate exp(-x): def fk_exp_inv(x, k): return (-x)**k /factorial(k) def exp_inv(x): return np.exp(-x) animate_series(fk_exp_inv, M = 0, N = 30, xmin = 0, xmax = 15, ymin = -0.5, ymax = 1.4, n = 200, exact = exp_inv) """ Terminal> python animate_Taylor_series.py (output is a plot (animation) """