马青公式
马青公式
π=16arctan1/5-4arctan1/239
这个公式由英国天文学教授约翰·马青于1706年发现。他利用这个公式计算到了100位的圆周率。马青公式每计算一项可以得到1.4位的十进制精度。因为它的计算过程中被乘数和被除数都不大于长整数,所以可以很容易地在计算机上编程实现。
还有很多类似于马青公式的反正切公式。在所有这些公式中,马青公式似乎是最快的了。虽然如此,如果要计算更多的位数,比如几千万位,马青公式就力不从心了。下面介绍的算法,在PC机上计算大约一天时间,就可以得到圆周率的过亿位的精度。这些算法用程序实现起来比较复杂。因为计算过程中涉及两个大数的乘除运算,要用FFT(Fast Fourier Transform)算法。FFT可以将两个大数的乘除运算时间由O(n2)缩短为O(nlog(n))。
用马青公式计算Pi至小数点后100位程序(Delphi)
program Pi_Value;
{$APPTYPE CONSOLE}
//将Pi计算精确小数点后100位
//Machin公式
//Pi=16arctan(1/5)-4arctan(1/239)
uses
SysUtils;
const
N=100;
S=2*N+50;
aNum=5;
bNum=239;
type
Num=array [1..S] of byte;
//初始化数组
procedure AZero(var arr:Num);
var
i:smallint;
begin
for i:=1 to S do
arr:=0;
end;
//除法
procedure Division(var arr:Num;const b:smallint);
var
c,y,i:smallint;
begin
c:=0;
for i:=1 to S do
begin
y:=arr+c*10;
c:=y mod b;
arr:=y div b;
end;
end;
//加法
procedure Addition(var arr:Num;const b:Num);
var
i,y,c:smallint;
begin
c:=0;
for i:=S downto 1 do
begin
y:=arr+b+c;
if y>=10 then
begin
c:=1;
arr:=y-10;
end
else
begin
c:=0;
arr:=y;
end;
end;
end;
//减法
procedure Minus(var arr:Num;const b:Num);
var
i,y,c:smallint;
begin
c:=0;
for i:=S downto 1 do
begin
y:=arr-b-c;
if y<0 then
begin
c:=1;
arr:=10+y;
end
else
begin
c:=0;
arr:=y;
end;
end;
end;
var
tag:boolean;
a,b,Ra,Rb,t:Num;
i,j:smallint;
begin
AZero(t);
Ra:=t;Rb:=t;
tag:=true;
writeln('计算中,请等待......');
for i:=1 to N do
begin
a:=t;b:=t;
a[1]:=16;b[1]:=4;
for j:=1 to i*2-1 do
begin
Division(a,aNum);
DiVision(b,bNum);
end;
Division(a,i*2-1);
Division(b,i*2-1);
if tag then
begin
tag:=false;
Addition(Ra,a);
Addition(Rb,b);
end
else
begin
tag:=true;
Minus(Ra,a);
Minus(Rb,b);
end;
end;
Minus(Ra,Rb);
writeln('计算结果如下:');
writeln(Ra[1],'.');
for i:=2 to N+1 do
write(Ra);
readln;
End.