How to get many places of pi from Machin's Equation?
Mark Dickinson
dickinsm at gmail.com
Sat Jan 9 10:57:05 EST 2010
On Jan 9, 11:31 am, "Richard D. Moores" <rdmoo... at gmail.com> wrote:
> Machin's Equation is
>
> 4 arctan (1/5) - arctan(1/239) = pi/4
> [...]
>
> Is there a way in Python 3.1 to calculate pi to greater accuracy using
> Machin's Equation? Even to an arbitrary number of places?
Here's some crude code (no error bounds, possibility of infinite
loops, ...) that computes pi to 1000 places using Machin's formula and
the decimal module. The last few digits will be bogus, and should be
ignored.
from decimal import Decimal, getcontext
def atan(x):
# reductions
reductions = 0
while 100*abs(x) > 1:
reductions += 1
x /= 1 + (1+x*x).sqrt()
# Taylor series
sum = 0
xpow = x
x2 = x*x
k = 1
while True:
term = xpow/k
oldsum = sum
sum += term
if sum == oldsum:
break
k += 2
xpow *= -x2
return sum * 2**reductions
getcontext().prec = 1000
one = Decimal(1)
print(16*atan(one/5) - 4*atan(one/239))
More information about the Python-list
mailing list