【问题标题】:sin with taylor series in python在 python 中与泰勒级数一起犯罪
【发布时间】:2013-11-28 05:00:05
【问题描述】:

这是我的代码:

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"

【问题讨论】:

  • 有什么问题? math.factorial(1999) is 太大而无法转换为浮点数。大约是 10^5733。 float 的最大值是 sys.float_info.max,我打赌你的系统大约是 10^308。
  • 您可以使用递归计算as:a[i] = -a[i-1] x**2 / 2i / (2i + 1)
  • @SteveJessop 例如,当我想计算 sin 30 时,我的输入是 0.523 。但它显示“OverflowError: long int too large to convert to float”
  • @RuggeroTurra 你看到我最后的评论了吗?!
  • 输入无关紧要,无论输入值如何,您的代码都会计算factorial(1999)(以及一堆其他数字太大而无法转换为float)。当您将float 除以整数时,Python 会尝试将整数转换为浮点数。它失败了。

标签: python trigonometry taylor-series


【解决方案1】:

这只是为了绘图:

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 个循环,取决于 xa 变为 0。

【讨论】:

    【解决方案2】:

    正弦泰勒级数的正确答案

    # 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
    

    【讨论】:

    • 泰勒级数是一个总和,因此您需要将 y 初始化为零并在循环中添加 y += ...。否则,除了几个错别字,它看起来不错。
    • y=((-1)**k)*(x**(1+2*k))/factorial(1+2*k) 行中,您需要更改为y= y + ( (-1)**k) * (x**(1+2*k) ) / factorial(1+2*k),这样就可以了。很棒的在线人!
    • @ElbertVillarreal 你需要初始化y
    • 当然鲍里斯,只是想改进线路。泰勒级数不是一件容易的事,这条线对理解很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2017-08-21
    • 2011-11-04
    相关资源
    最近更新 更多