In [here] and [here], the interesting equations are introduced to compute the math constant . Let’s review that the following equation:
It can be also equivalent to the following:
Compared to previous implementations, here will use Python to validate the first equation, to see how many iterations we need to approach the .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/env python from math import e x = 0 while True: x += 1 t = 1 + 1.0 / x s = 1 for y in xrange(0, x): s *= t # x times if abs(s - e) < 1e-4: # break if precision satisfies print x, "->", s break |
#!/usr/bin/env python from math import e x = 0 while True: x += 1 t = 1 + 1.0 / x s = 1 for y in xrange(0, x): s *= t # x times if abs(s - e) < 1e-4: # break if precision satisfies print x, "->", s break
To my surprise, the equation is not very efficient, it takes longer to converge to a reasonable-precision value of . In fact, is an infinite loopless irrelation which cannot be definitely computed using finite iterations.
The above tells us that it needs 13591 iterations in order to reach a value which has error less than 1e-4. The final value is 2.71818183219
Be careful if you simply increase the precision (i.e. 1e-8) because you might not get what you want. It might take longer to jump out of the loop or it might not be able for such to happen because of the well-known floating precision problem that almost any programming language has i.e. after a certain iterations, the precision will not improve anyway.
However, since the exponential can be efficiently expressed in Python using operator **, e.g. can be computed using expression a ** b in python. The above code can be shortened and improved:
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/env python from math import e x = 0 while True: x += 1 t = 1 + 1.0 / x s = t ** x # faster if abs(s - e) < 1e-4: print x, "->", s break |
#!/usr/bin/env python from math import e x = 0 while True: x += 1 t = 1 + 1.0 / x s = t ** x # faster if abs(s - e) < 1e-4: print x, "->", s break
See also: Simple and Efficient C Program to Compute the Mathematic Constant E (Euler’s number)
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: One Simple Equation to Compute e, base of the natural logarithm
Next Post: HTA-based Date Calculator, First Gift to My Son.