Euler's Number with 100 Digit Precision (Python)

vegaseat 3 Tallied Votes 2K Views Share

This short Python program calculates Euler's number e, the base of natural logarithms, to a precision of at least 100 digits in this case. To get the precision needed, the Python module decimal is used. The result is compared to a published result.

ddanbe commented: Nice! +15
# Euler's number e, the base of natural logs
# e is the sum of this infinite series:
# e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ...
# or simplified ...
# e = 2 + 1/2! + 1/3! + 1/4! + ...
# to get higher floating point precision use the module decimal
# tested with Python25     vegaseat     08jan2008

import decimal as dc

# set the precision
dc.getcontext().prec = 101

factorial = 1
euler = 2
for x in range(2, 150):
    factorial *= x
    euler += dc.Decimal(str(1.0))/dc.Decimal(str(factorial))

print "Eulers number calculated and 100 digit reference below:"

print euler

# e from http://www.gutenberg.org/etext/127  (up to 1 million places)
e = "2.7182818284590452353602874713526624977572470936999595749669676277\
240766303535475945713821785251664274"

print e

"""
my output --->
Eulers number calculated and 100 digit reference below:
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
"""
Stefan_3 0 Newbie Poster
You can just use sympy (e.g., 2000 digits):

import sympy
print sympy.N(sympy.E, 2000)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Starting with Python version 3.3 the decimal module has been rewritten in pure C and is much faster.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.