The series comes from the power series of
Arctan(x) = x - x3/3 + x5/5 - x7/7 ... with x = 1 yielding
Pi / 4 = 1 - 1/3 + 1/5 - 1/7 ...
Multiplying by 4 gives the series you show above. Notice that the numerator in each new term is always 4 and the denominator is always 2 more than the previous term so using a while loop something along the line of this should work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
double total = 0;
long int dem = 1;
bool isPositive = true;
while ( fabs(total - 3.141592d) < 0.0000005d )
{
if ( isPositive )
{
total += 4.0 / dem;
}
else
{
total -= 4.0 / dem;
}
isPositive = !isPositive;
dem += 2;
}
|
Notice that using a while loop requires you to already know
pi accurately to test against your running total in the condition of the loop. A more sophisticated approach could use a for loop by analyzing the series itself to figure out how many terms to add. Consider the following theorem from calculus:
If for the series
∑an an→ 0 as
n→infinity and the terms alternate in sign and decrease in magnitude monotonically to zero, i.e.,
|an| > |an+1| then the series converges and the error in the partial sum obtained by truncating the series is less in magnitude than the first term omitted. That is,
if
S = ∑an and Pn = a0 + a1 + a2 + ... + an then the magnitude of the error =
| S - Pn | < | an+1 |
As noted by
kev82 the general term has the form
(-1)(i+1) * 4/(2*i-1) with the index i starting at i=1 so what we want is
| S - Pn | < | an+1 | = | (-1)(n+2) * 4/(2*n+1) | < .000001
where I am starting the index at zero.
Simplifying we have
4 / (2*n + 1) < .000001
4 / .000001 < 2 * n + 1
4000000 < 2 * n + 1
3999999 < 2*n
1999999.5 < n
Thus if we were to add two million and one terms of the series we should have the desired accuracy.