圆周率的现代计算机求法(C语言) Label:Research
C语言求圆周率π
公式法1
#include <stdio.h>
#include <math.h>
int main(){
float term,result=1;
int n;
for(n=2;n<=100;n+=2){
term=(float)(n*n)/((n-1)*(n+1));
result*=term;
}
printf("pi的值为:%f\n", 2*result);
return 0;
}
pi的值为:3.141594上面的代码,先计算π/4的值,然后再乘以4,s=-s; 用的很巧妙,每次循环,取反,结果就是,这次是正号,下次就是负号,以此类推。
随机数法
#include<stdio.h>
#include<stdlib.h>
int main(){
double x,y;
int m=0,n=10000000,i;
srand(time(0));
for(i=0;i<n;i++){
x=(double)rand()/RAND_MAX;
y=(double)rand()/RAND_MAX;
if(x*x+y*y<1)m++;
}
printf("%lf\n",4.0*m/n);
return 0;
}
800位精度
#include<stdio.h>
long a=10000,b,c=2800,d,e,f[2801],g;
int main(){
for(;b-c;) f[b++]=a/5;
for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)
for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);
scanf("%s");
return 0;
}

这个比较出名的程序,三行语句求PI
按公式PI/2 = ∑ (n! / (2n+1)!!) 计算Pi
计算2800项就可以精确到小数点后800位
正常的写法是
#include "stdio.h" long b,c,d,e,f[2801]; void main(){ for (int i = 0; i < 2800; i++) f[i] = 2000; f[2800] = 0; for (c = 2800; c > 0; c -= 14) { d = 0; for (b = c; b > 0; b--) { d += f[b] * 10000; f[b] = d % (2*b-1); d /= (2*b-1); if (b > 1) d *= (b-1); } printf("%.4d", e + d / 10000); e = d % 10000; } }
更多算法请参考https://www.guokr.com/blog/444081/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!

浙公网安备 33010602011771号