2

I am attempting to write a Python program which will produce an approximation for e using a Taylor series to a user-defined length (e.g. 100 decimal places) and print all 100 digits. However, the output is never longer than 15 decimal places, which is python's default precision for numpy.e. How could I resolve this? Below is the code I was using.

import math

precision = int(input("Number of decimal places = "))
e = 0
s = 1
i = 1
while s > (10**(-1*precision)):
    e = e + s
    s = 1/math.factorial(i)   # e = 1 + 1/1! + 1/2! + 1/3! + ...
    i = i + 1
print(e)
  • 1
    with `decimal` module? – Jean-François Fabre Oct 09 '18 at 16:06
  • Also try out mpmath http://mpmath.org/ – Mochan Oct 09 '18 at 16:20
  • Due to the inefficiency of the formula `1 + 1/1! + 1/2! + 1/3! + ...` I would recommend Brothers' Formulae, found at the bottom of [this page](https://www.intmath.com/exponential-logarithmic-functions/calculating-e.php) as it will be more efficient. –  Oct 09 '18 at 16:32
  • Possible duplicate of [Increasing floating point precision in Python](https://stackoverflow.com/questions/21079282/increasing-floating-point-precision-in-python) –  Oct 09 '18 at 16:52
  • You should use `decimal.Decimal` for this for an arbitrary-length decimal representation, not `float`, which uses a fixed-size, binary floating-point representation. – juanpa.arrivillaga Oct 09 '18 at 20:35

1 Answers1

1

I think you can use sympy and mpmath.

First to figure out the number of terms we need from the error in Taylor series at x=0 and evaluated at 1,

1/n! e^1 < 1e-100

and taking n=75 is enough. Though we can just use 100 and this should also be good enough.

In sympy we create the Taylor series of e^x at 0 and then evaluate it at 1,

import sympy, mpmath

f = 0
for i in range(0, 100):
    f += 1/sympy.factorial(i)

mpmath.mp.dps = 100

print(mpmath.mpf(f))

which gives me the value of

2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
Mochan
  • 1,329
  • 1
  • 13
  • 27