求pi方法总结

 

 

 

古今中外,求Pi的方法主要有三类主要的方法:

1,正多边形逼近法

2,迭代法(级数法)

3,蒙特卡洛法(随机模拟)

方法一不便用程序实现,方法二和三均可用程序语言实现,实现方法如下:

方法二(迭代法):

//求pi 使用迭代法 pi/4=1-1/3+1/5-1/7+1/9-。。。
#include<stdio.h>
#include<math.h>
int main(int argc, char const *argv[])
{
    double PI=0,term=1,n=1;
    int sign=1;
    while(fabs(term)>=pow(10,-6)){
        PI+=term;
        n=n+2;
        sign=-sign;
        term=sign/n;
    }
    printf("PI=%10.8f\n",PI*4);
    return 0;
}
//求pi,使用迭代法 pi/2=1+1/3+(1/3)*(2/5)+(1/3)*(2/5)*(3/7)+...
//An=An-1*((n-1)/(2*n-1))
#include<stdio.h>
#include<math.h>
int main(int argc, char const *argv[])
{
    double PI=0,term=1,n=1;
    while(fabs(term)>=pow(10,-6)){
        PI+=term;
        n++;
        term=term*((n-1)/(2*n-1));
    }
    PI=PI*2;
    printf("PI=%10.8f\n",PI);
    return 0;
}

方法三(蒙特卡洛方法)【参考《算法与程序设计》一书】:

//求pi,使用蒙特卡洛法,使用随机模拟结果统计来求得pi的近似值
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char const *argv[])
{
    double n,c=0;
    //srand声明在stdlib.h,time声明在time.h
    //srand作用使用当前时间作为随机数发生器的种子值
    srand(time(0));
    scanf("%lf",&n);
    for (int i = 0; i <=n; ++i)
    {
      //RAND_MAX定义在stdlib.h中,代表rand函数返回的最大值
      //rand函数定义在stdlib.h中
        double x=-1.0+2.0*rand()/RAND_MAX;
        double y=-1.0+2.0*rand()/RAND_MAX;
        if (x*x+y*y<1.0)
        {
            ++c;
        }
    }
    double PI=(4*c)/n;
    printf("%f\n",PI);
    return 0;
}

 

 

转载于:https://www.cnblogs.com/fanxinglanyu/p/10278514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值