ARTICLE AD BOX
import math
import matplotlib.pyplot as plt
import numpy as np
m=50
def taylor_cos(x,n):
sum=0
for i in range(0, n):
sum=sum+ (((-1)**i) * (x**(2*i)) / math.factorial(2*i))
return sum
X=[]
Y=[]
arr=[]
for N in range(1,m):
for x_i in np.linspace(0,N*5,500):
if abs(math.cos(x_i)-taylor_cos(x_i,N))>10**-4:
arr.append((N,x_i))
X.append(N)
Y.append(x_i)
break
coeffs = np.polyfit(X, Y, 1)
fit = np.poly1d(coeffs)
print(coeffs)
plt.figure(figsize=(10,10))
plt.grid(True,alpha=0.3)
plt.axhline(0,color='gray',linewidth=0.5)
plt.scatter(X,Y,color='black',s=10)
plt.plot(X, fit(X), color='red', linewidth=1, linestyle='--')
plt.show()
I wanted to investigate the relationship between the number of Taylor series terms and the x_i when it starts to diverge. I used 10^-4 as a threshold. For this one, the line looks pretty good enter image description here, but for higher threshold, like 10^-8 enter image description here, very weird behavior appears for larger n. I think it is due to cancelations of big terms for large n where "big number"-"super big number" ~= 1, as a consequence, Python cannot hold too many digits and drop them. So the question, how to make the code more capable for handling smaller thresholds.
