Estimating e in Python

A while ago I wrote a post on estimating Pi using a variety of methods. As a sort of follow-up I will now write a post on estimating e, or Euler’s Number, in Python. I won’t try to summarize what e is or what it is used for as Wikipedia has a comprehensive article on the subject.
The Code
Let’s dive straight into the code which lives in a single file called e.py. (At least you can’t accuse me of using overly long filenames). You can clone/download the source code from the GitHub repository.
This is the first part of the source code.
Near the top of the file I have defined a constant called E15DP which is a string containing e to 15 decimal places. This will be used as a definitive value to compare with values we calculate. The name is all upper case to denote that it should be considered as a constant.
Next we have a few colour constants to output text to the console in various colours.
The main function consists of four function calls to estimate e using various methods. All but the first are commented out for now as we’ll run them one at a time.
The print_as_text function takes a value for e and converts it to a string with 15 decimal places. It then prints it after the definitive value, with correct digits in green and incorrect ones in red.
First Expansion
The first function to calculate e is expansion_1 which implements this formula...
...with a value of n = 100000.
We now have enough to run with this command.
Running the program
python3 e.py
The output is:
As you can see this gives us 4dp of accuracy; you might like to experiment with different values of n.
Second Expansion
Now let’s try another expansion to implement this formula with n = 0.000000001.
Comment out expansion_1() in main, uncomment expansion_2() and run the program again. This is the output.
This gives us 5dp of accuracy but again you can try different values of n.
Newton’s Series
Now let’s move on to the third method, Newton’s Series, for which the formula is:
This means we start off with n = 0, set e to 1/n!, increment n and then keep adding 1/n! to e for as long as we want. (n! means the product of all integers up to and including n, for example 4! = 4 x 3 x 2 x 1 = 24. Incidentally 0! = 1.) This is the function.
Uncomment newtons_series() in main and run the program.
Sir Isaac gives us 9dp of accurancy with a maximum value of n = 12.
Brothers Formula
As with π people are still working on ways to calculate e and I’ll finish off with this impressive recently discovered method, Brothers Formula, devised as recently as 2004.
As with Newton’s Series this is the sum of an infinite series although rather more complex.
The extra complexity pays off though: we only need to count to 8 to get 15dp (possibly more) of accuracy.
For updates and random ramblings please follow me on Bluesky.
No AI was used in creating the code, text or images in this article.















