Pi Values Using Leibniz Formula

I am still in the learning process of C++, and I have this assignment due Monday. My problem is that I have no idea how to get started. Here is the homework I was assigned:

One formula to calculate π expresses it as an infinite series of the form
π = ((4/1) - (4/3)) + ((4/5) - (4/7)) + ((4/9) - (4/11)) + ((4/13) - (4/15)) ...
Print the value of π after every fourth calculation, for the first 2000 terms of this series (500 output values). For convenience, your output should insert a newline after every five values, making a table where every row displays five values.

I see the pattern of the formula, and I know I would want to use nested loops in this case to make the table and include all of the calculations, I'm just very very stuck. I just need a little assistance, thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <math.h>
using namespace std;
int main(){
	
	double pi=0;
	int c=0;
	
	for(int i=1;i<=4000;i+2){
		pi=pi+(pow(-1,i+1))*(4/i);
		++c;
		if(c==4){
			cout<<pi<<endl;
			c=0;
		}		
	}
	return 0;
}
Maybe I didn't understand correctly OP, but, as a first idea, I guess this fits best what she wanted. Now only need to adapt to show values every n cycles.

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

int main (void)
{
    bool sw=true;
    double result = 0.0;
    int denominator=3, max=420000;

    result = 1.0 - (1.0/denominator);

    while (denominator < max)
    {
        denominator += 2;
        sw = !sw;
        (sw) ? (result -= (1.0/denominator)) : (result += (1.0/denominator));
    }

    printf ("Final: %.12f\n", 4 * result);

    return 0;
}    


http://coliru.stacked-crooked.com/a/48dc37cf7c6d2a26
Last edited on
My suggestion, for what it's worth.
Notice how the terms are grouped in the original question:
π = ((4/1) - (4/3)) + ((4/5) - (4/7)) + ((4/9) - (4/11)) + ((4/13) - (4/15)) ...

The terms alternate between positive and negative, but here they are grouped in pairs,
((4/1) - (4/3))
((4/5) - (4/7)) 
((4/9) - (4/11)) 


That is probably done both to improve accuracy, as well as avoiding large fluctuations in the resulting sum as it is being calculated.

You might do that something like this:
1
2
3
    // initial values
    double pi = 0;
    double d = 1.0;


Then inside the main loop, calculate the terms in pairs like this
1
2
3
    double term = 4.0/d - 4.0/(d+2.0);
    pi += term;
    d += 4.0;

After every second iteration, you will have calculated four terms, so output the current value of pi.


Topic archived. No new replies allowed.