[Python][Matplotlib] e^xのマクローリン展開のGIFアニメーションを作る
e^x のマクローリン展開
ソースコード
実行にはImageMagickのインストールが必要。
import math import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from tqdm import tqdm def calc_maclaurin_series_of_expx(x, n): result = 0 for k in range(n + 1): result = result + x**k / math.factorial(k) return result def main(): n_max = 20 fig = plt.figure() x = np.linspace(-10, 10, 100) def plot(n): plt.cla() y = np.ones_like(x) * np.nan for i in range(len(x)): y[i] = calc_maclaurin_series_of_expx(x=x[i], n=n) plt.plot(x, y, color='C0', zorder=5) plt.plot(x, np.exp(x), color='darkgray', linestyle='dashed', zorder=4) plt.ylim(-5000, 23000) plt.text(x=-5.0, y=10000, s='n={:>2d}'.format(n), fontsize=16) anim = animation.FuncAnimation( fig, plot, interval=300, repeat_delay=2000, frames=n_max ) anim.save('anim1.gif', writer="imagemagick") return if __name__ == '__main__': main()