I think you need to examine the mathematics a bit more closely. Each term of the series you described can be expressed:
a = (-1)
n * 4(2n + 1)
-n
And pi is the sum of a from n = 0 to n = infinity. You didn't need to introduce an extra variable called x - you could have just changed your
if statement to:
if ( loop % 2 == 0 )
Notice the (-1)
n term in the expression above - this means each iteration adds or subtracts a value of magnitude 4(2n + 1)
-n in alternation. So even though the sequence may converge to 3.141590, it won't approach from one side. Your loop condition:
while ( x <= 3.141590 || loop <=370000 )
expects that it starts below 3.141590, and strictly increases until it reaches that value and the loop terminates. But this isn't how the series actually works - so you need to redesign your loop. Try something like this:
while ( abs(pi - 3.141590) > 0.000001 )
You'll need to include the <cmath> header. This determines the magnitude of the difference between the calculated value and the value you want, and compares it with a tolerance (in this case 0.000001). If it's close enough (from either side), the loop terminates. But it only works if, at some point, the value of pi you're calculating is 3.141590 +/- 0.000001 - and unless you've analysed the series and you know that it converges to 3.141590, there's no guarantee that this condition will ever be true.
If you don't know exactly what it converges to, you should use a method that finds the change in pi between each iteration, and compares that with a tolerance to determine whether to terminate or not. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
double tol = 0.000001;
double cur = 0;
double prev;
int loop = 0;
do {
prev = cur;
// Then calculate cur
// Then increment the loop counter, update the denominator,
// output to the screen, etc.
} while ( abs(cur - prev) > tol );
cout << "Final value is: " << (cur + prev) / 2 << endl;
|
It could actually be written a bit more succinctly, you're only adding to/subtracting from cur at each iteration, but this way is nice and clear. Now in each iteration, a variable containing the previously calculated value is updated, at after each iteration, it's used to find the change in cur. As the series converges, this difference becomes smaller, until eventually it is less than or equal to tol. At this point, the loop terminates, and the final value is determined by taking the midpoint of cur and prev. This is a much better way of numerical computation than just expecting it to behave a certain way - in fact, if you know what it will converge to, there's no point running the loop in the first place except to see it happen before your eyes.