Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate e in Python [duplicate]

What would the easiest way to represent the following equation be?

Just to clarify, my question is asking for some code that calculates the answer to the equation.

There are two problems with this:

  1. The summation warrants an infinite loop which is impossible to get an answer from

  2. I hoping for a long, detailed answer (maybe to 40 digits or so).

like image 256
Beta Decay Avatar asked Dec 14 '22 23:12

Beta Decay


1 Answers

If you need more precision, you could try to use Fraction:

from fractions import Fraction # use rational numbers, they are more precise than floats
e = Fraction(0)
f = Fraction(1)
n = Fraction(1)
while True:
    d = Fraction(1) / f # this ...
    if d < Fraction(1, 10**40): # don't continue if the advancement is too small
        break
    e += d # ... and this are the formula you wrote for "e"
    f *= n # calculate factorial incrementally, faster than calling "factorial()" all the time
    n += Fraction(1) # we will use this for calculating the next factorial
print(float(e))

or Decimal:

from decimal import Decimal, getcontext
getcontext().prec = 40 # set the precision to 40 places
e = Decimal(0)
f = Decimal(1)
n = Decimal(1)
while True:
    olde = e
    e += Decimal(1) / f
    if e == olde: # if there was no change in the 40 places, stop.
        break
    f *= n
    n += Decimal(1)
print(float(e))

So here is e in 1000 places:

2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035044

To see more clearly what it does, here is its simplified version:

e = f = 1.0
for i in range(2, 16):
    e += 1.0 / f
    f *= i
print(e)
like image 119
user22698 Avatar answered Dec 31 '22 12:12

user22698