为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

函数式编程 2022-06-14 17:29:36
编写一个计算这个表达式的函数,将各项相加,直到下一项的绝对值小于指定的容差tol或直到最多nmax相加。我尝试了“从十进制导入十进制”和 float(c) 但它不起作用。import mathdef 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)/cOverflowError: int too large to convert to float
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

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


查看完整回答
反对 回复 2022-06-14
?
森栏

TA贡献1810条经验 获得超5个赞

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


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))


查看完整回答
反对 回复 2022-06-14
  • 2 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号