Arithmetic-geometric mean/Calculate Pi: Difference between revisions

added Pascal example
m (Automated syntax highlighting fixup (second round - minor fixes))
(added Pascal example)
Line 1,085:
{{out}}
<pre>%1 = 3.1415926535897932384626433832795028841971693993751058209749445923078164062878</pre>
 
=={{header|Pascal}}==
{{works with|FPC}}
{{libheader|GMP}}
The program expects as an input parameter the required number of decimal digits of '''''π''''' (32 ≤ N ≤ 1000000), default is 256 digits.
<syntaxhighlight lang="pascal">
program pi_digits;
{$mode objfpc}{$h+}{$warn 5091 off}
uses
SysUtils, Math, GMP;
 
const
MIN_DIGITS = 32;
MAX_DIGITS = 1000000;
 
var
Digits: Cardinal = 256;
 
procedure ReadInput;
var
UserDigits: DWord;
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.
</syntaxhighlight>
{{out}}
<pre>
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648
</pre>
 
=={{header|Perl}}==
73

edits