[4-1] 動画作成用のモジュールをインポートして、動画を表示可能なモードにセットします。
In [1]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
%matplotlib nbagg
[4-2] x=0.5における接線を描いて、その傾きを求める関数derivativeを定義します。
In [2]:
def derivative(f, filename):
fig = plt.figure(figsize=(4,4))
images = []
x0, d = 0.5, 0.5
for _ in range(10):
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(0, 1)
subplot.set_ylim(0, 1)
slope = (f(x0+d)-f(x0)) / d
linex = np.linspace(0, 1, 100)
image0 = subplot.text(0.5, 8, ('slope = %f' % slope))
image1, = subplot.plot(linex, f(linex), color='blue')
image2 = subplot.scatter([x0,x0+d],[f(x0),f(x0+d)])
def g(x):
return f(x0) + slope * (x-x0)
image3, = subplot.plot([0,1], [g(0),g(1)],
linewidth=1, color='red')
image4 = subplot.text(0.3, 1.05, ('slope = %f' % slope))
images.append([image0, image1, image2, image3, image4])
d *= 0.5
ani = animation.ArtistAnimation(fig, images, interval=1000)
ani.save(filename, writer='imagemagick', fps=1)
return ani
[4-3] 二次関数 y=x*x を用意して、関数derivativeを呼び出します。
GIF動画ファイル「derivative01.gif」が作成されます。
In [3]:
def f(x):
y = x*x
return y
derivative(f, 'derivative01.gif')
Out[3]: