这是我的代码:
import math
x=float(( input ('x ? ' )))
n = 1000 #a big number
b=0
for i in range (n):
a=(((((-1)**i))*(x**((2*i)+1)))/(math.factorial((2*i)+1)))
b+=a
print (b)
但它不起作用并显示此错误:
"OverflowError: long int too large to convert to float"
答案 0 :(得分:2)
这是一种可能的实施方式:
def mysin(x, order):
a = x
s = a
for i in range(1, order):
a *= -1 * x**2 / ((2 * i) * (2 * i + 1))
s += a
return s
这只是为了绘图:
import numpy as np
vmysin = np.vectorize(mysin, excluded=['order'])
x = np.linspace(-80, 80, 500)
y2 = vmysin(x, 2)
y10 = vmysin(x, 10)
y100 = vmysin(x, 100)
y1000 = vmysin(x, 1000)
y = np.sin(x)
import matplotlib.pyplot as plt
plt.plot(x, y, label='sin(x)')
plt.plot(x, y2, label='order 2')
plt.plot(x, y10, label='order 10')
plt.plot(x, y100, label='order 100')
plt.plot(x, y1000, label='order 1000')
plt.ylim([-3, 3])
plt.legend()
plt.show()
它受到数值不稳定和下溢的影响,因为过了一会儿(~100个循环,取决于x
)a
变为0。
答案 1 :(得分:1)
正确的泰勒系列答案
# calculate sin taylor series by using for loop in python
from math import*
print "sine taylor series is="
x=float(raw_input("enter value of x="))
for k in range(0,10,1):
y=((-1)**k)*(x**(1+2*k))/factorial(1+2*k)
print y