Oliver.T
Oliver.T

Reputation: 1

having trouble getting correct output from approximation formula in C

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double get_Pi(double accuracy)
{
    double Pi_estimate = 0;
    double increment = 0;
    double i = 0;
    int s = -1;


      while(fabs(increment) > accuracy)
     {

            increment = s*(1/(2*i+1));
              Pi_estimate = Pi_estimate + increment;
             s = -s;
             i++;
       }

       double offset = 1.0;
       Pi_estimate = Pi_estimate + offset;
       return 4*Pi_estimate;
       }



 int main()
{
   double accuracy;
     printf("\nhow accurate do you want Pi? ");
       scanf("%lf", &accuracy);
         double approx = get_Pi(accuracy);
       printf("%.10lf", approx);
        return 0;
      }

By inputting a certain decimal you should get pi to + or - the precision you inputted but the output is always 4.00000.

Upvotes: 0

Views: 79

Answers (2)

GM1
GM1

Reputation: 491

This question is very similar to C++ Pi Approximation using Leibniz Formula, which I believe is what you're looking for (despite it being a C++ question).

Your while loop never enters, since this condition can't happen unless accuracy is negative (0>accuracy) so you get result of (Pi_estimate =1)*4 = 4

Upvotes: 1

dbush
dbush

Reputation: 223872

You're starting from 0 instead of 1 and adding instead of subtracting in the denominator of your term, you're calculating the new value of increment using integer operations instead of floating point, and your while loop never gets entered because increments starts at 0.

The correct formula is: pi / 4 = sum(k->inf) ((-1)^(k+1))/(2k-1)

So you would do this as:

double get_Pi(double accuracy)
{
    double Pi_estimate = 0;
    double increment;
    double i = 1;    // start at 1
    int s = 1;       // start with positive factor

    do {    // do the check at the bottom instead of the top
        increment = s*(1.0/(2.0*i-1));    // use floating point constants to prevent integer division
        Pi_estimate = Pi_estimate + increment;
        s = -s;
        i++;
    } while(fabs(increment) > accuracy);

    // no need to add an offset
    return 4*Pi_estimate;
}

Upvotes: 1

Related Questions