Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate 



π


{\displaystyle \pi }

.

With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:





π
=



4


a
g
m

(
1
,
1

/



2



)

2




1
−

∑

n
=
1


∞



2

n
+
1


(

a

n


2


−

g

n


2


)





{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}



This allows you to make the approximation, for any large   N:





π
≈



4


a

N


2




1
−

∑

k
=
1


N



2

k
+
1


(

a

k


2


−

g

k


2


)





{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}



The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of 



π


{\displaystyle \pi }

.

with javascript_semantics
requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed)
include mpfr.e
 
mpfr_set_default_precision(-200) -- set precision to 200 decimal places
mpfr a = mpfr_init(1),
     n = mpfr_init(1),
     g = mpfr_init(1),
     z = mpfr_init(0.25),
     half = mpfr_init(0.5),
     x1 = mpfr_init(2),
     x2 = mpfr_init(),
     v = mpfr_init()
mpfr_sqrt(x1,x1)
mpfr_div(g,g,x1)    -- g:= 1/sqrt(2)
string prev, curr
for i=1 to 18 do
    mpfr_add(x1,a,g)
    mpfr_mul(x1,x1,half)
    mpfr_mul(x2,a,g)
    mpfr_sqrt(x2,x2)
    mpfr_sub(v,x1,a)
    mpfr_mul(v,v,v)
    mpfr_mul(v,v,n)
    mpfr_sub(z,z,v)
    mpfr_add(n,n,n)
    mpfr_set(a,x1)
    mpfr_set(g,x2)
    mpfr_mul(v,a,a)
    mpfr_div(v,v,z)
    curr = mpfr_get_fixed(v,200)
    if i>1 then
        if curr=prev then exit end if
        for j=3 to length(curr) do
            if prev[j]!=curr[j] then
                printf(1,"iteration %d matches previous to %d places\n",{i,j-3})
                exit
            end if
        end for
    end if
    prev = curr
end for
if curr=prev then
    printf(1,"identical result to last iteration:\n%s\n",{curr})
else
    printf(1,"insufficient iterations\n")
end if
