如何解决“溢出错误:int 太大而无法转换为浮点数”?

编写一个计算这个表达式的函数,将各项相加,直到下一项的绝对值小于指定的容差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


函数式编程
浏览 121回答 2
2回答

MYYA

首先,我不明白,为什么你认为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

森栏

尝试将数字转换为十进制,例如:import mathimport decimaldef 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 bprint(sin_taylor(math.pi/2))print(math.isclose(sin_taylor(math.pi/2), 1))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python