Calculating Pi

For class we need to write a program that takes in an input (n) that determines the number of terms in the approximation of the value of pi and outputs the approximation. The program also needs a for loop to calculate this until the user wants to quit using the program.

The formula for pi that was given to us was.

pi = 4 [ 1 - 1/3 + 1/5 - 1/7 + 1/9 ... +((-1)^n)/(2n+1) ]

The main problem we have is, how to write the formula into the program. We are lost and will take any advice or help at this point, thanks in advance!
You have the formula right there: every successive n adds 4*((-1)^n)/(2n+1).

That is the theory. Finding the most numerically accurate way to compute that with or without floating point numbers is an another challenge.
Thanks, might have to take a zero on this one.. we are lost!
You should be able to do it pretty easily with a for loop


Basically something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double pi( int n )
{
     double pi = 4.0 , decimal = 1.0;
     while( n > 2 )
    {
        decimal -= ( 1.0 / ( 2.0 * n + 1 ) );
        --n;
        decimal += ( 1.0 / ( 2.0 * n + 1 ) );
        --n;
    }
    if( n > 0 )
        decimal -= ( 1.0 / ( 2.0 * n + 1 ) );
    return( pi * decimla );
}


I could be wrong though but it looks to me like the formula is

4 * (1 / 1 + 2n ) The inside part would be all the fractions added up ex 1 / 1 - 1 / 3 + 1 / 5 - 1/7

So if n was 3 then it would be ( I gave it the 0 by default so I start at 1 and go to 3 ) When I say I gave it 0 by default I mean I initialized it to 1
4 * ( -1/7 + 1/5 - 1/3 + 1/1 ) = 4 * ( 0.72380952380952380952380952380952 ) = 2.8952380952380952380952380952381

Am I misunderstanding the formula you provided?

Also yes I did do it in reverse order

But basically if n is even say for example 4

That would mean
1 - + - +

And I started with -

And an odd would end in a -
so lets look at 3
1 - + -

Topic archived. No new replies allowed.