3

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.

Votes + Comments
Nice!
# 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
"""
2
Contributors
2
Replies
25
Views
9 Years
Discussion Span
Last Post by vegaseat
0

You can just use sympy (e.g., 2000 digits):

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

0

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

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.