所有小数位[Python]

时间:2018-10-30 14:40:22

标签: python python-3.x decimal

我正在尝试创建一个E(数学常数)逼近脚本。但这只给我15个小数位。然后,我添加了Decimal(),该位数增加了小数位数,但仍然限制为50个小数位数。有什么办法可以打印所有小数。 (如果没有,限制是什么?)


这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

将浮点结果投射到Decimal当然是不够的。您必须使用Decimal个对象执行所有计算,并且,如果需要很高的精度,则必须告诉decimal

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'

答案 1 :(得分:-2)

尝试使用numpy中的float64。它们提供了更高的精度