zoukankan      html  css  js  c++  java
  • 计算pi的方法

    zxp学长告诉我两种计算pi值得办法,第一种是pi/4=1-1/3+1/5-1/7……(课本上的传统方法)

    第二种方法是

    这种方法的证明

    (以上由zxp学长找的资料给我的……)

    用C++写出这两种方法求解pi的过程,然后比较这两种方法收敛的速度

     1 #include<iostream>
     2 #include<iomanip>
     3 #include<math.h>
     4 using namespace std;
     5 int main(){
     6     double pi1=0;
     7     double pi2;
     8     for(double i=0;i<1500000;i++){//the method in text book should use more than a million times 
     9         pi1=pi1+(1/(2*i+1))*((int)i%2?-1:(1));
    10     }
    11     pi1=pi1*4;
    12     double t=sqrt(2);
    13     double d=2;
    14     double m=t;
    15     for(int i=0;i<100;++i){
    16         pi2=(d)/m;
    17         t=sqrt(2+t);
    18         m*=t;
    19         d*=2;
    20     }//the method zxp give me use less than a thousand times;
    21     cout<<setiosflags(ios::fixed)<<setprecision(10)<<pi1<<endl;
    22     cout<<setiosflags(ios::fixed)<<setprecision(10)<<pi2*2<<endl;
    23     return 0;
    24 }
    View Code

    从计算的结果来看,用第一种加减的方法,计算到了10000次以后,最多也只能精确到小数点后4位之前,而且结果还不正确。直到计算到百万次以后,结果才比较令人满意(还是不算很精确)

    运用第二种方法,在100次计算以内,就能精确到小数点后20位以后。

  • 相关阅读:
    如何实现浏览器内多个标签页之间的通信?
    vue组件库的基本开发步骤(源代码)
    vue组件库的基本开发步骤
    Websocket原理
    TCP和UDP的区别
    一句话概括 tcp三次握手
    简单说一下你对http和https的理解
    .Ajax(async异步与sync同步)
    get和post请求方式的区别
    面试易忽略状态码
  • 原文地址:https://www.cnblogs.com/zhanzhao/p/3553278.html
Copyright © 2011-2022 走看看