問題設定

以下の4つの式についてマクローリン展開し、x=0付近での近似度を確かめる。

  1. y=sin(x)
  2. y=cos(x)
  3. y=log(1+x)
  4. y=e^x

実装

In [1]:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import theano
import theano.tensor as T
In [2]:
input = np.linspace(-5, 5, 1000)
In [3]:
x = T.dscalar('x')
In [4]:
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

y=sin(x)

In [11]:
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()

y=cos(x)

In [6]:
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()

y = log(1+x)

In [17]:
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()

y=e^x

In [14]:
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付近において、たしかに元の関数とマクローリン展開の式が近似することがわかった。

In [ ]: