Search code examples
cmathwhile-loopsum

how to evaluate pi in c using while loop


I'm trying to write a code in c to approximate the value of pi using a while loop. I know it is much easier to do so with a for loop but I'm trying to do so using while. the formula I'm using to do so is in link below: https://www.paulbui.net/wl/Taylor_Series_Pi_and_e and the code I wrote looks like this:

#include <stdio.h>
#include <math.h>
int main(){
   long n=10;
   while(n>0){
      double a=0;
      a+=((pow(-1,n))/((2*n)+1));
      n=n-1;
      printf("%ld",4*a);
   }
return 0;
}

the reason I used long and double type is that I wanted to do the approximation to a good preciseness but first I should do st for this problem. thanks in advance.


Solution

  • You have to move a initialization before loop and make stop condition - for example, evaluating current summand. Also it is worth to calculate sign incrementally without using pow:

    double a=0;
    double eps= 1.0e-6; //note this series has rather slow convergence
    n = 0;
    double tx = 1.0;
    double t = 1.0;
    while(abs(tx)>eps){
       tx = t / (2*n+1)); 
       a+= tx;
       printf("%f",4*a);
       n++;
       t = - t; 
    }