-3

I am trying to create an E (mathematical constant) approximation script. But it only gives me 15 decimals places. I then added a Decimal() which increased the number of decimal places but was still limited to 50 decimal places. Is there any way to print all decimals. (If not, what's the limit?)


Here's my code:

from decimal import *
e=1
x = input("Iterations:")
x=int(x)
while 1==1:
    e=1 + e/x
    x -= 1
    if (x <= 0):
        break

print(Decimal(e)) # only prints 50 decimal places
VinceKaj
  • 335
  • 4
  • 13
  • Possible duplicate of [how can i show an irrational number to 100 decimal places in python?](https://stackoverflow.com/questions/4733173/how-can-i-show-an-irrational-number-to-100-decimal-places-in-python) – Georgy Oct 30 '18 at 15:00

2 Answers2

1

Casting your floating point result to Decimal is, of course, not enough. You have to perform all of the computations using Decimal objects and, if you need a large precision, you have to tell decimal about that

In [73]: from decimal import Decimal, getcontext                                        
In [74]: getcontext().prec = 70                                                         
In [75]: e = Decimal(1)                                                                 
In [76]: x = Decimal(200000)                                                            
In [77]: while x>0: 
    ...:     e = Decimal(1)+e/x 
    ...:     x = x-Decimal(1)                                                           
In [78]: e                                                                              
Out[78]: Decimal('2.718281828459045235360287471352662497757247093699959574966967627724076')
In [79]: str(e)[:52]                                                                    
Out[79]: '2.71828182845904523536028747135266249775724709369995'
gboffi
  • 22,939
  • 8
  • 54
  • 85
-2

Try float64 from numpy. They offer more precision

  • No, [almost all platforms map Python floats to IEEE-754 “double precision"](https://docs.python.org/3/tutorial/floatingpoint.html#representation-error). See also [the reference for numeric types](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) – gboffi Oct 30 '18 at 14:56