2013-11-14 50 views
0

這是我的代碼:罪與泰勒級數蟒蛇

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" 
+2

什麼這個問題? 'math.factorial(1999)'*太大而無法轉換爲浮點數。大約10^5733。 'float'的最大值是'sys.float_info.max',我將在你的系統上下注10^308。 –

+1

你可以使用遞歸計算'a's:'a [i] = -a [i-1] x ** 2/2i /(2i + 1)' –

+0

@SteveJessop for ex amaple當我想計算罪30 我的輸入是0.523。 但它顯示「OverflowError:long int太大,無法轉換爲float」 – Hippo

回答

1

這是一個可能的實現:

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() 

plot sin x

從數值不穩定和下溢症,因爲一段時間(〜100圈,dependig上xa成爲正弦泰勒級數0

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