求PI值,PI/4 = 1 - 1/3 + 1/5 - 1/7 + ……
我的代碼
//求PI值,PI/4 = 1 - 1/3 + 1/5 - 1/7 + ……
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
//double get_PI(int n)
//{
// double sum = 0, temp;
// for(int i=1; i<(n+1); i++)
// {
// //temp = 1/(2*i- 1);//雖然temp定義爲double型,但等式右邊i爲int,所以計算結果爲取整,應用1.0
// //temp = 1.0/(2*n - 1);
// temp = 1.0/(2*i- 1);
// //if(temp < 1e-8) break;
// //cout << "temp = " << temp << endl;
// sum += pow(-1.0,i+1)*temp;
// //cout << "sum = " << sum << endl;
// }
// return sum*4;
//}
double get_PI()
{
double sum = 0, temp = 1, n = 1, k = 1;
while(temp > 1e-6)
{
temp = 1.0/(2*n - 1);
//cout << "temp = " << temp << endl;
sum += k*temp;
//cout << "sum = " << sum << endl;
k = -k;
n++;
}
return sum*4;
}
int main()
{
//int a;
//cin >> a;
//cout << get_PI(a) << endl;
cout << get_PI() << endl;
system("pause");
return 0;
}
同類型題
//求PI值,PI/4 = 1 + 1/3 + 1/3*2/5 +1/3*2/5*3/7 + ……
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
double get_PI()
{
double sum = 1, temp = 1, n = 1;
while(temp > 1e-6)
{
temp *= n/(2*n+1);//前一項*後一項
sum += temp;
n++;
}
return sum*2;
}
int main()
{
cout << get_PI() << endl;
system("pause");
return 0;
}
總結
1、在我的代碼中第一個求PI的函數需要輸入一個整數用來計算PI/4最後一項的的值,雖然可以自行決定輸入的大小,但這種求PI近似值的方法,項數越多,計算值約精確,同時耗時也越多;參考代碼中使用while(fabs(t)>1e-8),即給最後一項限制了大小,無需手動輸入,只要精確值夠小就可以。由於使用1e-6和1e-8運行結果都是3.14159,所以我的代碼第二個函數中使用了while(temp > 1e-6),減少運算時間;
2、k = 1, k = -k 的用法可以代替pow(-1.0, n)的使用;
3、temp = 1/(2i- 1);//雖然temp定義爲double型,但等式右邊i爲int,所以計算結果爲取整,應用1.0,改爲:temp = 1.0/(2i- 1);