I'm attempting to approximate the constant e using 100,000 iterations and display the results where i is in multiples of 10,000 ranging from 10,000 to 100,000.
The code I have is this:
import math
e = 0
i = 0
while i < 100001:
e += 1 / (math.factorial(i))
i += 1
if i % 10000 == 0:
print("The approximation using", i, "iterations is: ", e)
There's two problems with this:
1.) The code takes forever to run, but I think that might be expected.
2.) I'm getting the same value for the approximation no matter how many iterations I use. Here's the beginning portion of my output:
The approximation using 10000 iterations is 2.7182818284590455
The approximation using 20000 iterations is 2.7182818284590455
The approximation using 30000 iterations is 2.7182818284590455
.. and so on. How can I fix this?
For context, this is an intro-level programming problem that only incorporates loops.
Edit: Noticed that I had my i and e sections backwards in my while loop. Fixed. Still encountering the issue of the number not changing, though.
Float numbers are encoded in 64 bits with means you can't keep iterating and getting new digits of e.
one alternative would be to use arbitrary precision arithmetic (GMP)
Install gmpy2 :
Refractor your code :