import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import theano
import theano.tensor as T
input = np.linspace(-5, 5, 1000)
x = T.dscalar('x')
def maclaurin(y):
f = theano.function(inputs=[x], outputs=y)
d_y1 = T.grad(cost=y, wrt=x)
d_f1 = theano.function(inputs=[x], outputs=d_y1)
d_y2 = T.grad(cost=y, wrt=x)
d_f2 = theano.function(inputs=[x], outputs=d_y2)
d_y3 = T.grad(cost=y, wrt=x)
d_f3 = theano.function(inputs=[x], outputs=d_y3)
mac = f(0) + d_f1(0)*x + d_f2(0)*(x**2)/2 + d_f3(0)*(x**3)/6
f_mac = theano.function(inputs=[x], outputs=mac)
return f, f_mac
f, f_mac = maclaurin(T.sin(x))
teach = [f(input[i]) for i in range(len(input))]
mac = [f_mac(input[i]) for i in range(len(input))]
plt.plot(input, teach, color="blue")
plt.plot(input, mac, color="green")
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.show()
f, f_mac = maclaurin(T.cos(x))
teach = [f(input[i]) for i in range(len(input))]
mac = [f_mac(input[i]) for i in range(len(input))]
plt.plot(input, teach, color="blue")
plt.plot(input, mac, color="green")
plt.xlim(-1, 1)
plt.ylim(-0.5, 1.5)
plt.show()
f, f_mac = maclaurin(T.log(1+x))
teach = [f(input[i]) for i in range(len(input))]
mac = [f_mac(input[i]) for i in range(len(input))]
plt.plot(input, teach, color="blue")
plt.plot(input, mac, color="green")
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.show()
f, f_mac = maclaurin(T.exp(x))
teach = [f(input[i]) for i in range(len(input))]
mac = [f_mac(input[i]) for i in range(len(input))]
plt.plot(input, teach, color="blue")
plt.plot(input, mac, color="green")
plt.xlim(-1, 1)
plt.ylim(0, 2)
plt.show()
x=0付近において、たしかに元の関数とマクローリン展開の式が近似することがわかった。