-1

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;
}
melpomene
  • 79,257
  • 6
  • 70
  • 127
Ben French
  • 11
  • 4

3 Answers3

1

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.

P.W
  • 24,743
  • 6
  • 32
  • 69
1

You need to increment i value in while loop.

Your looping condition while(i < max) is always satisfied (infinite loop). So the value of i or max should be changed inside the loop to ever end the loop.

vinayawsm
  • 831
  • 8
  • 27
1

Your code has undefined behavior:

scanf("%f", &epsilon);

scanf %f takes a float *, not double *. The correct format for double * is %lf.


Your loop condition while (i<max) is equivalent to while (1) as neither i nor max change their value inside the loop.

This also means sum is always 4:

sum = (4.0/(2.0*i-1));
// 4 / (2 * 1 - 1) = 4 / (2 - 1) = 4 / 1 = 4

pi += sum;

also has undefined behavior: pi is uninitialized.

melpomene
  • 79,257
  • 6
  • 70
  • 127