python - 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
解决方案
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'
推荐阅读
- python - 拆分多个分隔符插入到数据框python
- python - 如何使用flask和jinja2在mapbox gl中渲染自定义多面体
- html - VBA 代码 - Selenium - 使用 ng-binding 抓取网页
- stack - 栈容量,修改推送程序
- c++ - lambda 通过引用捕获更改没有可变关键字的变量
- amazon-cognito - 在更改密码时放大自定义电子邮件
- python - python中的动态内联电报键盘
- python-3.x - 类函数上的 timeit
- stored-procedures - Fedex Ship Manager 存储过程参数无法识别
- python-3.x - 在带有 M1 处理器的 Macbook Pro 上,进程以退出代码 132(被信号 4:SIGILL 中断)完成 - Tensorflow