How to resolve the algorithm Arithmetic-geometric mean/Calculate Pi step by step in the Pascal programming language
How to resolve the algorithm Arithmetic-geometric mean/Calculate Pi step by step in the Pascal programming language
Table of Contents
Problem Statement
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 }
.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Arithmetic-geometric mean/Calculate Pi step by step in the Pascal programming language
Source code in the pascal programming language
program AgmForPi;
{$mode objfpc}{$h+}{$b-}{$warn 5091 off}
uses
SysUtils, Math, GMP;
const
MIN_DIGITS = 32;
MAX_DIGITS = 1000000;
var
Digits: Cardinal = 256;
procedure ReadInput;
var
UserDigits: Cardinal;
begin
if (ParamCount > 0) and TryStrToDWord(ParamStr(1), UserDigits) then
Digits := Min(MAX_DIGITS, Max(UserDigits, MIN_DIGITS));
f_set_default_prec(Ceil((Digits + 1)/LOG_10_2));
end;
function Sqrt(a: MpFloat): MpFloat;
begin
Result := f_sqrt(a);
end;
function Sqr(a: MpFloat): MpFloat;
begin
Result := a * a;
end;
function PiDigits: string;
var
a0, b0, an, bn, tn: MpFloat;
n: Cardinal;
begin
n := 1;
an := 1;
bn := Sqrt(MpFloat(0.5));
tn := 0.25;
while n < Digits do begin
a0 := an;
b0 := bn;
an := (a0 + b0)/2;
bn := Sqrt(a0 * b0);
tn := tn - Sqr(an - a0) * n;
n := n + n;
end;
Result := Sqr(an + bn)/(tn * 4);
SetLength(Result, Succ(Digits));
end;
begin
ReadInput;
WriteLn(PiDigits);
end.
You may also check:How to resolve the algorithm RPG attributes generator step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the Julia programming language
You may also check:How to resolve the algorithm Pentomino tiling step by step in the Phix programming language
You may also check:How to resolve the algorithm Long primes step by step in the 11l programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the RLaB programming language