I need help writing a program to approximate pi

I am having trouble writing a program that displays the results of the following two approximations of pi.

pi = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11)
pi = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13)

Can anyone give me some help? Thanks
something should flash to you directly

1-3-5-7-9-11-13- is a serie .

C++ provide a very powerful technique to do that .

Recursion .

You will have a method that will call itself .

You can look in Google for c++ recursion PI .

or simply try this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>
using namespace std;

double pi (double);

int main()
{
 cout << "Enter n to value of pi: "; int n; cin>>n;
 cout << pi(n) << endl;

 return 0;
}


double pi (double n)
{
 if (n==1)
  return 4*1;
 else
  return ( 4*(pow(-1,n+1)*(1/(2*n-1))) + pi(n-1) );
}
Last edited on
And this will give me the output of PI = 2.97605
PI = 3.28374 ?
The higher the length of your serie , the higher precision you have . You must think that pi comes from a circle . The serie tells you that it can approximate by saying that a circle is a polygon having a lot of edges , so more edges more accurate will be your PI estimation . Enter 100 , then 300 , then 1000 , then 4000 . Of course the recursion has a limitation to the max stack frames so if you enter 10000 you will have a stack frame overflow.

Did it help you ?
Here is another possible solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
	double pi1 = 0;
	int sign=1;
	for (int i=1; i<=11; i+=2)
		{
		pi1 += sign*4.0/i;
		sign *= -1;
		}	
	cout << pi1 << endl;
	
	double pi2 = 0;
	sign=1;
	for (int i=1; i<=13; i+=2)
		{
		pi2 += sign*4.0/i;
		sign *= -1;
		}	
	cout << pi2 << endl;
}
Topic archived. No new replies allowed.