計算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位以后。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM