import math
def exp_taylor(x, n):
c = 1.0
f = 1.0
for i in range(n):
c /= (i+1)
f += c * x**(i+1)
return f
x = 0.5
print('x = ', x)
print('1st = ', exp_taylor(x, 1))
print('2nd = ', exp_taylor(x, 2))
print('3rd = ', exp_taylor(x, 3))
print('4th = ', exp_taylor(x, 4))
print('5th = ', exp_taylor(x, 5))
print('6th = ', exp_taylor(x, 6))
print('7th = ', exp_taylor(x, 7))
print('8th = ', exp_taylor(x, 8))
print('exact = ', math.exp(x))
x = 0.5 1st = 1.5 2nd = 1.625 3rd = 1.6458333333333333 4th = 1.6484375 5th = 1.6486979166666667 6th = 1.6487196180555554 7th = 1.6487211681547618 8th = 1.6487212650359622 exact = 1.6487212707001282
# numpy
import numpy as np
# matplotlibのおまじない
from matplotlib import pylab as plt
x = np.linspace(0.0, np.pi, 100)
y = np.cos(x)**2
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7fc02c1c73d0>]