I’m trying to code a program that approximates pi using a certain equation. However, when I go run the code it outputs 4.8731472566 instead of 3.1415924576 and I was wondering if there were any mistakes in my code. Here’s what I have so far
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
printf("n = ");
scanf("%d", &n);
double pi = 0.1;
double pi_1, pi_2, pi_3, pi_4, pi_5 = 0; //sets varibles that represent 4.0/((8*i)+1), etc. equal to zero
i = 0; // sets i equal to zero
while(i <= n){ // starts a loop with i is less than non-negative interger n
pi_1 = 4.0/((8*i)+1); //setting them equal to their respective parts of the equation
pi_2 = 2.0/((8*i)+4);
pi_3 = 1.0/((8*i)+5);
pi_4 = 1.0/((8*i)+6);
pi_5 = 1.0;
int j = 0; //creating new interger j
while(j <= i){ //as long as j isn't greater than i
pi_5 = pi_5*(1.0/16); //it will run the last part of the formula
j++;
}
pi += pi * (pi_1 - pi_2 - pi_3 - pi_4 - pi_5); //sets pi = to the entire formula
i++;
}
printf("PI = %.10fn", pi);
return 0;
}
And here is the equation…
I’ve tried changing pi to different integers like 0.001 and 1 and that didn’t work
3
Answers
There are a few things wrong in the way you calculate
pi
.pi
should start from0.0
andpi += pi * (pi_1 - pi_2 - pi_3 - pi_4 - pi_5);
should not contain thepi *
part and you should multiply bypi_5
instead and thewhile
loops condition should bej < i
.I came up with this function (which makes use of
<math.h>
, instead of calculating the power with a loop). I am usingk
here since it is the same as used at the link I provided in the function to the formula.Making this its own function makes it easier to use it in multiple spots. And btw if you post code on stackoverflow (or you just want to debug it yourself) it is easier and faster to test it if you provide some constant value for e.g.
n
(or what I calledsteps
in my function) instead of usingscanf()
to get it from the user each time you run it.Reviewing the code, there seems to be a lot of unneeded variables and looping involved. I do see that there has been an answer added, but I thought I would go ahead and toss in my simplified version which also utilizes the math.h file and math library.
A simple "for loop" is substituted in the refactored code, and using the summation formula, only the "pi" variable is necessary. Following was some sample output.
The only additional thing to point out is that when using the "math.h" include file, a reference in the linking portion of the build needs to be done, usually with an "-lm" as "m" is the math function library.
In addition to what others suggest:
Tip: rather compute
pi_5
with a somewhat expensive loop or with a slow1/pow(16,i)
call, use the prior value to quickly form the new one.