PI equation in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • volunteerguy
    New Member
    • Oct 2006
    • 9

    PI equation in C

    Hello All,

    i'm currently working on a program wich asks the user to input an integer value of "n" to determine what value of the denominator in an equation for PI to work to.

    this is written in c, and I have all the basic input, output, function calls etc; however, i'm relatively new to c and i'm a bit confused on how to turn the equation below into a c expression with variable input.

    PI = 4(1 + 1/3 - 1/5 + 1/7 etc... (where int n is the value of the denominator to continue to)

    anyone able to help? Thanks a lot!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The thing that changes about that equation is the denominator, also remember that

    PI = 4(1 + 1/3 - 1/5 + 1/7 ...) = 4 + 4/3 - 4/5 + 4/7 ...)

    also I think you have you pluses and minuses the wrong way round it should be

    PI = 4(1 - 1/3 + 1/5 - 1/7 ...) = 4 - 4/3 + 4/5 - 4/7 ...)


    So you need a (for) loop controling the denominator. Then have a variable that is initialised to zero and for each iteration of the loop add (or subtract) another term of the series

    Code:
    INITIALISE PI to 0
    FOR NUMBER OF SERIES TERMS REQUIRED
       ADD SERIES TERM TO PI
    END FOR

    Comment

    • volunteerguy
      New Member
      • Oct 2006
      • 9

      #3
      my bad on the +'s and -'s that was simply a typo...

      so if i was to write a for loop something like

      int PI;
      int n; //number of iterations
      int den_val; //denominator value

      for(PI = 0; n > den_val; PI += den_val) {
      /*code*/
      }

      and assuming that is correct, i'm still a little confused on how to incorporate the equation into the loop. I understand the 4 - 4/3 + 4/5 etc... but i'm not quite sure how to tie that into the loop and have the the +'s and -'s alternating.

      i hope that makes sense, and i appreciate your help.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        You loop is not quite right, also remember PI is 3.141...., try and store it in a int and it will be 3. Your loop control variable should be an int but you will need to calculate PI as a double value.

        The = and - are easy, just have a boolean variable (are you using C or C++?) to maintain an indication of what to do with the next term, also note that 1 = 1/1

        Code:
        GET NUMBER OF TERMS REQUIRED nTerm
        SET ADD = TRUE
        SET PI = 0
        
        FOR EACH REQUIRED TERM
            IF ADD == TRUE
                SET PI = PI + VALUE OF TERM
                SET ADD = FALSE
            ELSE
                SET PI = PI - VALUE OF TERM
                SET ADD = TRUE
        END FOR
        
        PRINT PI
        Note that the nth term of the series has the value 4/(n*2-1), verify this for yourself.

        Comment

        • volunteerguy
          New Member
          • Oct 2006
          • 9

          #5
          i'll give that a whirl, i see what you're getting at

          i'm coding in standard C

          i appreciate the help!

          Comment

          • volunteerguy
            New Member
            • Oct 2006
            • 9

            #6
            so here is what i've come up with...
            it seems to me like it should execute correctly, but somewhere something is causing my output to be bogus large numbers; however, it will compile... does anyone see my error?
            any help will be appreciated!
            Code:
            #include<stdio.h>
            
            void pi(int n, double *pi_value, int *iterations); //declare function
            
            int main (void)
            {
                int n;                    //number of terms
                int iterations;        //number of actual loop iterations in pi
                double pi_value;   //computed value of pi
                
                printf("Please enter an odd integer n;  ")'
                printf("quit with a non-positive or even integer:\n");
            
               /*-- Read n and display pi.  Quit with a non-positive n.  --*/
               scanf("%d", &n);
               while(n>0 && n%2)
               {
                   pi(n, &pi_value, &iterations);
                   printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
                   scanf("%d", &n);
               }
               
               return(0);
            }  
            
            voi pi(int n, double *pi_value, int *iterations)
            {
                int i;
                int ADD = 1 // 1 = true & 2 = false
               
                for(i=0; i<n; i++)
                {
                    pi_value += (4/((n*2)-1));
                    ADD = 2;
                    break;
                }
                for(ADD == 2)
                {
                    pi_value -= (4/((n*2)-1));
                    ADD = 1;
                    break;
                }
                (*iterations)++
            }

            Comment

            • volunteerguy
              New Member
              • Oct 2006
              • 9

              #7
              please ignore the code from my previous post, i typed it in a rush and realized it had many glaring syntax errors, try this one instead...

              Code:
              #include<stdio.h>
              
              void pi(int n, double *pi_value, int *iterations); //declare function
              
              int main (void)
              {
                  int n;                    //number of terms
                  int iterations = 0;        //number of actual loop iterations in pi
                  double pi_value = 0;   //computed value of pi
                  
                  printf("Please enter an odd integer n;  ")'
                  printf("quit with a non-positive or even integer:\n");
              
                 /*-- Read n and display pi.  Quit with a non-positive n.  --*/
                 scanf("%d", &n);
                 while(n>0 && n%2)
                 {
                     pi(n, &pi_value, &iterations);
                     printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
                     scanf("%d", &n);
                 }
                 
                 return(0);
              }  
              
              void pi(int n, double *pi_value, int *iterations)
              {
                  int i;
                  int ADD = 1 // 1 = true & 2 = false
                 
                  for(i=0; i<n; i++)
                  {
                      switch(ADD) 
                      {
                         case 1:
                           *pi_value += (4/((n*2)-1));
                           ADD = 2;
                           break;
                         case 2:
                           *pi_value -= (4/((n*2)-1));
                            ADD = 1;
                       {   break;
                  }
                  (*iterations)++;
              }

              Comment

              • Banfa
                Recognized Expert Expert
                • Feb 2006
                • 9067

                #8
                You have 5 errors (ignoreing the minor syntax errors you posted, once you have compiling code copy and paste is a good way to get it to the forum posting box).

                They are all in this section of code, I am going to tell you about 4 of them. Once I have done this you should be able to find the other one by running your program.

                Code:
                void pi(int n, double *pi_value, int *iterations)
                {
                    int i;
                    int ADD = 1; // 1 = true & 2 = false
                   
                    for(i=0; i<n; i++)
                    {
                        switch(ADD) 
                        {
                           case 1:
                             *pi_value += (4/((n*2)-1));
                             ADD = 2;
                             break;
                           case 2:
                             *pi_value -= (4/((n*2)-1));
                              ADD = 1;
                         {   break;
                    }
                    (*iterations)++;
                }
                On a point of style it is slightly more normal to use the value 0 for false but your use of 2 does not stop the program working.
                1. Code:
                  for(i=0; i<n; i++)
                  This doesn't stop the program working but I suspect it does make it so that it is not doing what you think it is doing. Note n is always odd, making me think you were asking for the highest term denominator to use, however this loop uses it as the number. Does the series always require an odd number of terms or would it work with an even number? Actually this series works with any number of terms > 0. If n = 7 the text message give the impression of creating this series

                  PI = 4(1 - 1/3 + 1/5 - 1/7)

                  but the code actually evaluates this

                  PI = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13)

                  Decide if you want to input the number of terms (change text but the loop stays the same) or the value of the maximum denominator (change loop, possible change text to to make it clear what is being input).
                2. Code:
                  (*iterations)++;
                  You have put it outside the loop, it only ever executes once for each function call, with the current loop it will always end up equal to n.
                3. Code:
                  *pi_value -= (4/((n*2)-1));
                  You have used the variable n, this is the number of terms to use, not the current term. You need tobase the calculation on the variable i which is the one that changes. But note a straight swop will not work because the initial value of i is 0. You have (correctly) used the formula for the xth term 4 / ((x*2)-1), so the first term is 4 / ((1*2)-1), but your control variable value does not start at 1 ir starts at 0, you need to add 1 to it 4 / (((i+1)*2)-1), a little algibra will so that this is equal to 4 / ((i*2)+1)
                4. Code:
                  *pi_value -= (4/((i*2)+1));
                  *pi_value is a floating point type but i (or n) are int and 4, 2 and 1 are integer constants.. The calculation is done in integer arithmatic and then converted to a double. In integer arithmatic all decimal places are dropped, the first term evaluates to 4/1=4 the second to 4/3=1 and all further terms evaluate to 0 giving a result of 3. You need to force the compiler to use floating point arithmatic.

                  You can either cast the controlling variable to double
                  Code:
                  *pi_value -= (4/(((double)i*2)+1));
                  Using floating point constants instead of integer constants
                  Code:
                  *pi_value -= (4./((i*2.)+1.));

                Like I said there is 1 more error, see if you can find it (hint try 2 calculations in a row).

                And finally 1 more point of style
                Code:
                printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
                A double only has a precision of 15 decimal places, asking it for 81 is wishful thinking, also if you don't want a field width just don't specify one, no need to set it to 0 so this line would be better as

                Code:
                printf("%17d:   %.15f with %d iterations\n", n, pi_value, iterations);
                You can test this, set the 15 to a 16, the last digit will always be 0

                Comment

                Working...