# Pie.py: calculate pi, using arithmetic-geometric mean
# See: en.wikipedia.org/wiki/Gauss-Legendre_algorithm
from mpmath import *   # high floating point precision library
# Note: below much is converted to high precision by use
mp.dps = 70            # num of digits for calculations
N = 4                  # number of steps
print("Prec: ", mp.dps, ", iters: ", N)
a = mpf(1)
g = 1/sqrt(2)
t = 1/mpf(4)
p = 1
for k in range(1, N+1):
    an = (a + g)/2     # arithmetic mean
    gn = sqrt(a*g)     # geometric mean
    tn  = t - p*(a - an)**2
    pn = 2*p
    a, g, t, p = an, gn, tn, pn
print("   ", ((a + g)**2)/(4*t))  # approximate pi
print("\npi:", pi)                # exact pi