[英]sin with taylor series in python
這是我的代碼:
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"
這僅用於繪圖:
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。
正弦泰勒級數正確答案
# 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.