# Exercise 5.39 # S(x;M,N) = sum f_k(x) for k=M,....,N import numpy as np import matplotlib.pyplot as plt import glob import os def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): # A) Remove existing image files for file in glob.glob("*.png"): os.remove(file) # B) Set up plot plt.axis([xmin, xmax, ymin, ymax]) plt.xlabel("x") plt.ylabel("S(x;M,N)") # C) Define grid of x- and s-values x = np.linspace(xmin, xmax, n) s = np.zeros(n) # D) Plot points for k=M,...,N lines = plt.plot(x, fk(x,M)) for k in range(M,N+1): # Add one more term to Taylor series s = s + fk(x,k) # Update vertical plot values: lines[0].set_ydata(s) # Exact solution: plt.plot(x, exact(x), 'g') # Update drawing: plt.draw() # Save to file: plt.savefig("tmp_%04d.png" % (k-M)) # First example: Sin(x) exact = np.sin fk = lambda x,k: 1.0 * (-1)**k * x**(2*k+1) / np.math.factorial(2*k+1) M = 0 N = 40 xmin = 0 xmax = 13*np.pi ymin = -2 ymax = 2 n = 200 animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact) """ Terminal> convert -delay 40 tmp_*.png movie.gif """ """ # Second example: exp(-x) exact = lambda x: np.exp(-x) fk = lambda x,k: 1.0 * (-x)**k / np.math.factorial(k) M = 0 N = 30 xmin = 0 xmax = 15 ymin = -0.5 ymax = 1.4 n = 200 animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact) """ """ Terminal> convert -delay 40 tmp_*.png movie.gif """