首页 > 解决方案 > All decimal places [Python]

问题描述

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

标签: pythonpython-3.xdecimal

解决方案


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'

推荐阅读