How to calculate the value of pi accuratly using while loops

I need to calculate the value of pi accurately to six digits using the series pi=4-4/3+4/5-4/7+4/9-4/11... Honestly I have no idea how they want me to do with this. I know how to express a while loop but I haven't had any experience with the series they have given. Please help if you can, thanks:)
Maybe this will help

The i'th term of that sequence is given by the formula:

(-1)^(i+1) * 4/(2*i-1)

You want to repeatedly keep adding the next term until the total is correct to 6dp. I think that would be

fabs(total - 3.141592d) < 0.0000005d

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.
Last edited on
Topic archived. No new replies allowed.