Search code examples
cpiapproximation

Infinite series approximation of pi in C not terminating


Here is my code, when using print statements it appeared to be an infinite loop:

some potential issues i can troubleshoot are integer division, and perhaps figuring out if the algorithm terminates, and if it always has the correct output, perhaps there is some idiosyncrasy of the C language that I do not understand causing this issue?

From my understanding as the sum tends to negative infinity it will cause the break statement to be triggered ending the algorithm once it reaches an approximation of epsilon precision.

#include <stdio.h>

int main()
{

  double pi, sum, epsilon;
  long long i=1;
  long long max = 2147483647;
  printf("Pleas enter the desired accuracy epsilon : ");
  scanf("%f", &epsilon);
  while (i<max){
    if (i%2 == 0){
      sum = -4.0/(2.0*i-1);
    }else if (i%2 ==1){
      sum = (4.0/(2.0*i-1));
    }
    if (sum < epsilon){
      break;
    }
    pi += sum;
  }
  printf("The value of pi approximated to epsion : %f is %f\n", epsilon, pi);
  return 0;
}

Solution

  • You are not increment the value of i in your while loop. As a result its value always remains 1.

    Increment i after your processing is done before the closing } of the while loop.

    Initialize the values of pi, sum, epsilon so that you do not run into undefined behavior when you try to read their values for the first time.

    Also, with proper options enabled (-Wall with GCC) the compiler will warn you, that you are trying to read a float into a double.

    warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double *' [-Wformat=]
    
       scanf("%f", &epsilon);
    
              ~^   ~~~~~~~~
    

    So you have to use the correct conversion specifier: %lf instead of %f in your scanf statement.

    If you are not very particular about the number 2147483647 and just want a large value, you can also use ULLONG_MAX (from limits.h) to initialize max instead of hard-coding the value.