how do i do this, pls help.

Write a program that computes the value of the mathematical constant π, using the following series:
4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ......
The program should ask for the numbers of terms int n, then compute double pi using the first n terms.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <math.h>
using namespace std;

int main() {
	int i,n;
	cout << "Enter the number of terms.";
	cin >> n;
	double pi;
	for ( i =1;i<=n;i++)
	pi += pow(-1,i+1) * 4.0 / ( i );
	cout << pi;
	return 0;
	}


got this so far dunno what im doing :(
Last edited on
1
2
3
double pi = 0;
for ( i = 1; I <= n; i++ )
  pi += pow(-1,i+1) * 4.0 / ( 2*i - 1 );
There are a couple of errors. First, pi should be initialised with the value 0.
Second, the required series has the denominator 1, 3, 5, 7 etc. but the code above has 1, 2, 3, 4 etc.

You might also look at ways to make this more efficient. Since it may require millions or billions of iterations in order to get a reasonably accurate result, calling a function such as pow() each time is a very expensive use of resources. See if you can do this without the use of pow() or other functions.
Another method would be something like this
1
2
3
4
5
6
7
8
9
double compute_pi( const int PRECISION )
{
	double pi = 4.0;
	for( int i = 0; i < PRECISION; ++i )
	{
			pi += (i % 2 == 0 ? -4.0 : 4.0) / ( 3.0 + i * 2 );
	}
	return( pi );
}


http://ideone.com/BIl3aj

*on a side note I wouldn't suggest using pow it is a pretty advanced formula and could slow down your function if you had a really high n. Lets compare run times for 1e6 ( 1million ) Mine takes: .01 seconds Yours takes: .11 seconds so that would mean yours is 11x slower than mine.
Last edited on
Topic archived. No new replies allowed.