【问题标题】:How to solve "OverflowError: int too large to convert to float'?如何解决“溢出错误:int 太大而无法转换为浮点数”?
【发布时间】:2020-02-03 18:52:12
【问题描述】:

编写一个计算此表达式的函数,将各项相加,直到下一项的绝对值小于指定的容差tol 或最多添加nmax 项。

我尝试了“从十进制导入十进制”和 float(c),但它不起作用。

import math

def sin_taylor(x, tol=1e-7, nmax=100):

    b=0
    for i in range (nmax):
        e = float(2*i+1)
        c=float(math.factorial(e))
        #print(c)
        #print(b)
        a=((((-1)**i))*(x**(e))/c)
        b+=a
    return b

当我断言 sin_taylor(0)==0 时,它给出 0 但当我 断言math.isclose(sin_taylor(math.pi/2),0.999999943741051),它给出a=((-1)**i*d)/c OverflowError: int too large to convert to float

【问题讨论】:

  • 查看this answer 的类似问题。它可能会有所帮助。

标签: python taylor-series


【解决方案1】:

尝试将数字转换为十进制,例如:

import math
import decimal


def sin_taylor(x, tol=1e-7, nmax=100):
    decimal.getcontext().prec = 90
    b=0
    for i in range (nmax):
        e = (2*i+1)
        c=(math.factorial(e))
        a = (-1)**i*decimal.Decimal(x)**(e)/c
        b0 = b
        b += a
        if b0 == b:
            print(i)
            break
    return b


print(sin_taylor(math.pi/2))
print(math.isclose(sin_taylor(math.pi/2), 1))

【讨论】:

  • @Kisha 抱歉,不得不编辑我的解决方案,因为我在方程式 a=... 上犯了一个错误(我在一个地方使用了 1 而不是 i)。现在它应该可以工作了。
  • 另外,关于@aparpara - 他对 b 变得太小是正确的。对于您给定的 tol=1e-7 这很可能是唯一的问题。另一方面,如果您想拥有非常小的 tol 值(例如 1e-100),您仍然可能需要使用小数。但为此,您还需要更改 decimal.getcontext().prec- 我会将其添加到我的代码中。您可以通过在 aparpara 建议的 break-condtion 中添加 print(i) 来查看差异,而不是为 decimal.getcontext().prec 尝试不同的值。
【解决方案2】:

首先,我不明白,为什么你认为sin(math.pi/2) 应该接近0.999999999943741051?实际上,它必须正好是 1。

其次,您的算法中最突出的问题是,在某些时候a 变得如此之小,以至于将其添加到b 不会改变任何事情。如果此时打破循环,您将不会拥有这些超大的 c 值,如下所示:

def sin_taylor(x, tol=1e-7, nmax=100):
    b=0
    for i in range (nmax):
        e = float(2*i+1)
        c=float(math.factorial(e))
        #print(i, c, b)
        a=((((-1)**i))*(x**(e))/c)
        b0 = b
        b += a
        if b0 == b:
            break
    return b

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多