Search code examples
cpi

i want to write a program in C that will give PI using Wallis Formula


i want to write a program in C that will give PI using Wallis Formula

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

int main()
{
 long int i;
 double sum=1, term, pi = 0;
 /* Applying Formula */
 for(i=1;i< 1000000;i++)
 {
  term = pow((2*i),2)/((2*i-1)*(2*i+1));
  sum = sum * term;
 }
 pi = 2 * sum;
 printf("PI = %.10lf",pi);
 return 0;
}

i wrote that code and it keeps giving me PI = -inf


Solution

  • Your problem seems to be, that your integer variable i is a 4-Byte value. When
    the denominator ((2*i-1)*(2*i+1)) is evaluated, you get an overflow if i is greater than about 23170 (Sqrt(2^31) / 2). With the loop boundary set to 23170 your formula works. It also works when using an 8-Byte integer for i together with your original loop boundary.