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,但它无法正常工作。
答案 0 :(得分:1)
en_1 > 1e-6
永远不会评估为True
。 en_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