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__'
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
A
Decimal
object can't be sliced to get the individual digits. However a string can, so convert it to a string first.You may need to adjust
n
for the decimal point and desired digit range.You are trying to treat
pi
as an array, when it is aDecimal
. I think you are looking forquantize
:https://docs.python.org/2/library/decimal.htmlIf you'd like a faster pi algorithm, try this one. I've never used the Decimal module before; I normally use mpmath for arbitrary precision calculations, which comes with lots of functions, and built-in "constants" for pi and e. But I guess Decimal is handy because it's a standard module.
I got bored with how long the process it was taking (that 350-iteration loop is a killer), but the answer seems plain. A
Decimal
object is not subscriptable the way you have it.You probably want to turn it into a string first and then process that to get the digits:
You should also keep in mind that this truncates the value rather than rounding it. For example, with PI starting out as:
(about as much as I can remember off the top of my head), truncating the string at five significant digits will give you
3.1415
rather than the more correct3.1416
.