import numpy as np
import matplotlib.pyplot as plt
import scienceplots
#Warning : As of version 2.0.0, you need to add import scienceplots before setting the style (plt.style.use('science')).
plt.style.use(['science', 'notebook'])
def my_sin(x): # テーラ展開によるsinの計算
global n_ # グローバル変数
eps = 1.0e-6 # 収束判定条件
er = eps
m2 =1
s = x
t = s
while er >= eps:
m1 = m2+1
m2 = m1+1
t = -t*(x*x/m1/m2)
s = s+t
er = np.abs(t)
n_ = m1/2
return s
フォーマット付きで計算値を出力すると,
q = 180.0/np.pi
nx = 7 # 計算点数
print(f"{'No.':>3s} {'x [deg]':>8s} {'my_sin(x)':>10s}"\
f"{'sin(x)':>10s} {'error':>12s} {'N':>4s}")
dx = 15.0/q
for i in range(nx):
x = i*dx
y = my_sin(x)
print(f"{i+1:3.0f} {x*q:8.2f} {y:10.5f}"\
f"{np.sin(x):10.5f} {y-np.sin(x):12.8f} {n_:4.0f}")
nx2 = 6
xx = np.linspace(0.0, 90.0/q, nx2)
print(f"{'x [deg]:':>10s}",end=' ')
[print(f"{xx[i]*q:8.5f}",end=' ') for i in range(nx2)]
yy = np.empty(nx2)
yy[:] = [my_sin(xx[i]) for i in range(nx2)]
print("")
print(f"{'my_sin(x):':>10s}",end=' ')
[print(f"{yy[i]:8.5f}",end=' ') for i in range(nx2)]
print("")
print(f"{'sin(x):':>10s}",end=' ')
[print(f"{np.sin(xx[i]):8.5f}",end=' ') for i in range(nx2)]
print("")
print(f"{'error:':>10s}",end=' ')
[print(f"{yy[i]-np.sin(xx[i]):8.5f}",end=' ') for i in range(nx2)]
print("")