python - 搜索我为计算泰勒级数而编写的代码错误

标签 python

我的作业是编写一个代码,其中包含一个计算 sinx 泰勒级数并返回数量的函数。 该函数必须得到 (n,k),其中 n 是正弦的请求数,k 是函数必须在点后计算的数字。 首先我忽略了k,因为它很容易限制点后的数字,并写了一个只计算sinx taylor的函数,所以我给它一个特定范围的r(r是泰勒级数的每一句话):

def taylor(n,k):

  s= ((math.pi)/180)*n
  ex = s
  sign = 1
  factorial = 1
  sum=0
  i=1
  r=1

  while r>0.00000000000000000001 or r<0.0000000000000000000001 :
     r= ex*sign/factorial
     ex = ex*s*s
     sign = sign*(-1)
     factorial=factorial*(i+1)*(i+2)
     i= i+2
     sum = sum + r

  return sum

import math
print(taylor(45,1))

我只是不知道为什么如果我将 r 的数量设置为大于此值(即 0.1),我会收到此错误:

Traceback (most recent call last):

File "/Users/modern/Desktop/taylor.py", line 22, in <module>

print(taylor(45))

File "/Users/modern/Desktop/taylor.py", line 12, in taylor

r= ex*sign/factorial

OverflowError: int too large to convert to float

最佳答案

我很惊讶这是一个问题,因为我认为 r 在成为问题之前会低于容错。

请注意,您真正需要的是阶乘的倒数。您可以使用一个初始化为 fact_recip 的变量,而不是使用阶乘变量来除以

fact_recip = 1.0

r= ex*sign*fact_recp 一样使用

并通过

更新
fact_recip /= ((i+1)*(i+2))

这将处理您看到的错误,但我不确定舍入错误是否会成为问题。

关于python - 搜索我为计算泰勒级数而编写的代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616156/

相关文章:

python - 使用 Python 对 JSON 进行 Google App Engine 数据存储查询

python - IndexError : too many indices for array: array is 1-dimensional, 但在绘制网格时对 2 个进行了索引

python - 我应该如何使用 GEKKO 为 log 或 sqrt 建模?约束条件

python - pykinect2深度帧被截断

python - 从一个文件中获取信息并在 Python 中打印到另一个文件

python - del运算符如何在python中的列表中工作?

python - Tensorflow,try and except 不处理异常

Python:如何在表达式中创建列表理解后重新使用它们

python - 如何转换 datetime.strptime() 奇怪的日期格式(其中包含单词 "of")?

python - 如何修改我的代码以查找具有特定类的所有 <a> 标签的所有特定属性