Reputation: 79
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
I want to calculate e via this code, but it cannot work.
Upvotes: 0
Views: 615
Reputation: 45542
en_1 > 1e-6
will never evaluate to True
. en_1
just gets bigger and bigger. At some point you end up with numbers so large that Python can't handle the conversions. Instead compare to 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
This could be made much simpler:
e = n = fac = 1
while 1.0/fac > 1e-6:
fac *= n
e += 1.0/fac
n += 1
Upvotes: 1