编写程序求π的值

编写程序求π的值

 π的计算公式如下:

 

其中arctan用如下形式的级数计算:

 

直到级数某项绝对值不大于10-15为止;π和x均为double型。

此程序关键在于arctan()函数的编写

程序一:

 1 #include <stdio.h>
 2 #include <iostream>
 3 using namespace std;
 4 double power(double x, int n) {    //求x 的n 次幂
 5     double val = 1.0;
 6     while (n--) {
 7         val *= x;
 8     }
 9     return val;
10 }
11 
12 double arctan(double x) {
13     double sum = 0, pow = 0;
14     for (int i = 1; i > 0; i++) {
15         pow = power(x, 2 * i - 1) / (2 * i - 1);
16         if (pow < 1e-15) break;
17         sum += power(-1, i + 1)*pow;
18     }
19     return sum;
20 }
21 int main()
22 {
23     double pi;
24     pi = 16.0*arctan(1 / 5.0) - 4.0*arctan(1 / 239.0);
25     cout << pi;
26     return 0;
27 }
C++ Code

程序二:改进版

  观察到arctan的级数每项的“+”“-”号为:系数对4取余为1时,为“+”;余数不为1时为“-”。

 1 #include <stdio.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 double arctan(double x) {
 6     double f,sum=0;
 7     double e=x;
 8     int i = 1;
 9     while (e/i> 1e-15) {
10             f = e / i;
11             sum = (i % 4 == 1) ? sum + f : sum - f;
12             e *= x * x;
13             i += 2;
14     }
15     return sum;
16 }
17 
18 int main() {
19     double pi;
20     pi = 16.0*arctan(1 / 5.0) - 4.0*arctan(1 / 239.0);
21     cout << pi;
22     system("pause");
23     return 0;
24 }
C++ Code

程序三:使用C++库中的求arctan的函数

  #include <math.h> 中的 atan(double x) 函数求x的反正切值 或者

               atan2(double y,double x)  求y/x 的反正切值

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<math.h>
 4 using namespace std;
 5 int main() {
 6     double pi;
 7     pi = 16.0*atan(1/5.0) - 4.0*atan(1/239.0);
 8     //pi = 16.0*atan2(1 , 5.0) - 4.0*atan2(1 , 239.0);
 9     cout << pi;
10     system("pause");
11     return 0;
12 }
C++ Code

猜你喜欢

转载自www.cnblogs.com/pgzhang/p/9068947.html