""" This code does the same as animate_Taylor_series.py, but uses a FuncAnimation object to create the animation.""" import numpy as np from math import factorial import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin,xmax,n) """ When using this method, it is easiest to precompute all the s values and store them in a two-dimensional array. The function to update the frames will then simply get values out of this array and update the plot.""" s = np.zeros((n,N+1-M)) s[:,0] = fk(x,M) for k in range(M+1,N+1): s[:,k-M] = s[:,k-1-M] + fk(x,k) plt.plot(x,exact(x)) plt.axis([xmin,xmax,ymin,ymax]) lines = plt.plot(x,s[:,0]) def next_frame(frame): lines[0].set_ydata(s[:,frame]) return lines ani = FuncAnimation(plt.gcf(), next_frame, frames=range(M,N+1), interval=250) #ani.save('movie.mp4',fps=20) plt.show() 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,200,np.sin)