python中的泰勒系列罪
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19990274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:10:53 来源:igfitidea点击:
sin with taylor series in python
提问by Hippo
This is my code :
这是我的代码:
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)
but it doesn't work and shows this error:
但它不起作用并显示此错误:
"OverflowError: long int too large to convert to float"
回答by Ruggero Turra
This is one possible implementation:
这是一种可能的实现:
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
This is just for plotting:
这仅用于绘图:
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()
It suffers from numerical instability and underflow, since after a while (~100 loops, dependig on x
) a
becomes 0.
它受到数值不稳定和下溢的影响,因为一段时间后(~100 个循环,取决于x
)a
变为 0。
回答by Mehdi raza
correct answer of sine taylor series
正弦泰勒级数正确答案
# 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