PI with infinite series

So I have to create a program that calculates pi using the infinite series definition. This is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <iostream>
#include <cmath>

using namespace std;

int main() {

	cout << "This program calculates pi." << endl;
	double pi;

	for (int n = 1; n <= 1000; n += 2) {
		pi = (4 / n) - 4 / (n + 2);
		if (n % 100 == 0) {
			cout << "After " << n << " terms, the value of pi is " << pi << endl;
		}
	}
	
	system("pause");
	return 0;
}


It doesn't print out the result and I have no idea why...
Thanks in advance
I think your formula is a little bit off. pi = (4 / n) - 4 / (n + 2); this is identical to double pi = (4 / 1000) - 4 / (n + 2) which is the same as pi = (0) - 4 / (1002) which is the same as pi = 0 - 0 which is the same as pi = 0. The problems are 1) formula is wrong and 2) you are using integer division instead of floating point division.

The formula should be pi = 4/1 - 4/3 + 4/5 - 4/7 ...

So something like
1
2
3
4
5
6
7
8
double pi = 0.0;
int sign = 1;

for(int n = 1; n <= 1000; n += 2)
{
    pi += sign * 4.0 / n;
    sign = -sign; //go from adding to subtracting, and go from subtracting to adding
}


Another way would be
1
2
3
4
5
6
7
8
9
double pi = 0.0;
int sign = 1;

int const terms = 1000;
for(int n = 0; n < terms; ++n)
{
    pi += sign * 4.0 / (n << 1 + 1); //n << 1 == n * 2
    sign = -sign;
}
Last edited on
n begins as an odd number.
n gets incremented by 2 each time.
n will always be odd, and therefore will never be divisible by 100.

Also, be careful, because you're currently doing integer division on line 13. For the result of division to be floating point, either the numerator or the denominator needs to be a floating point (float or double) as well.

Otherwise the result will be truncated.

This will probably work more toward your liking:
pi = (4.0 / n) - 4.0 / (n + 2);
Although I think your algorithm for calculating Pi is wrong, but I guess that's another issue.
Last edited on
Topic archived. No new replies allowed.