-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
4

2 回答 2

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'
于 2018-10-30T16:03:28.160 回答
-2

Try float64 from numpy. They offer more precision

于 2018-10-30T14:45:41.587 回答