calcuale ---- OverflowError:long int太大而无法转换为float

时间:2016-10-18 15:22:23

标签: python python-2.7

en_1 = 1
n = 1
factorial = 1
invfactorial = 1
    while en_1 > 1e-6 :
        en = en_1 +invfactorial
        n = n + 1
        factorial = factorial * n
        invfactorial = float(1.0/factorial)
        en_1 = en 
print "e = %.5f"%en

我想通过此代码计算e,但它无法正常工作。

1 个答案:

答案 0 :(得分:1)

en_1 > 1e-6永远不会评估为Trueen_1变得越来越大。在某些时候,你最终得到的数字太大,Python无法处理转换。而是与invfactorial > 1e-6比较:

en_1 = 1
n = 1
factorial = 1
invfactorial = 1
while invfactorial > 1e-6:  # changed comparison
    en = en_1 +invfactorial
    n = n + 1
    factorial = factorial * n
    invfactorial = float(1.0/factorial)
    en_1 = en # don't need both en_1 and en

这可以简单得多:

e = n = fac = 1
while 1.0/fac > 1e-6:
    fac *= n
    e += 1.0/fac
    n += 1