def pi():
prompt=">>> "
print "\nWARNING: Pi may take some time to be calculated and may not always be correct beyond 100 digits."
print "\nShow Pi to what digit?"
n=raw_input(prompt)
from decimal import Decimal, localcontext
with localcontext() as ctx:
ctx.prec = 10000
pi = Decimal(0)
for k in range(350):
pi += (Decimal(4)/(Decimal(8)*k+1) - Decimal(2)/(Decimal(8)*k+4) - Decimal(1)/(Decimal(8)*k+5) - Decimal(1)/(Decimal(8)*k+6)) / Decimal(16)**k
print pi[:int(n)]
pi()
Traceback (most recent call last):
File "/Users/patrickcook/Documents/Pi", line 13, in <module>
pi()
File "/Users/patrickcook/Documents/Pi", line 12, in pi
print pi[:int(n)]
TypeError: 'Decimal' object has no attribute '__getitem__'
Tags:
如果你想要更快的pi算法,试试这个。我以前从未使用过Decimal模块;我通常使用mpmath来进行任意精度的计算,它附带了很多函数,并为pi和e内置了“常量”。但我想Decimal是一个方便的工具,因为它是一个标准模块。在
我对这个过程花了多长时间感到厌烦(350次迭代循环是个杀手),但答案似乎很简单。一个
Decimal
对象不能按您的方式订阅。在您可能需要先将其转换为字符串,然后再进行处理以获得数字:
您还应该记住,这个会截断值,而不是四舍五入。例如,当PI开始为:
^{pr2}$(大概是我脑子里能记住的),将字符串截断为5个有效数字将得到
3.1415
,而不是更正确的3.1416
。在您试图将
pi
视为一个数组,而它是Decimal
。我想你在找quantize
:https://docs.python.org/2/library/decimal.html相关问题 更多 >
编程相关推荐