求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);