[ create a new paste ] login | about

Link: http://codepad.org/V1M5Dn6e    [ raw code | output | fork | 2 comments ]

mohit_at_codepad - C, pasted on Apr 25:
// Print the value of pi
#include <stdio.h>
#include <stdlib.h>
//#define inline

// Integration (1+x^2)^-1 in limit[0-1] is pi/4

//inline double app_fun(double x) {
//  return 1 / (1 + x * x);
//}
#define app_fun(x) (1.0 /(1 + x * x))

int main() {
  int i = 0;
  const int NUM_ITER = 1000 * 1000;
  double sfun = 0.0;

  sfun += app_fun(0.0);
  for(i = 1; i < NUM_ITER; ++i) {
    double curx = 1.0 * i / NUM_ITER;
    sfun += 2 * app_fun(curx);
  }
  sfun += app_fun(1.0);

  printf("Value of pi is: %g\n", 2.0 * sfun / NUM_ITER);
  return 0;
}


Output:
1
Value of pi is: 3.14159


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Apr 25
This program produces the value of pi accurate to many places of decimals. To print more digits, replace print statement with
printf("Value of pi is: %1.20g\n", 2.0 * sfun / NUM_ITER); /* Print 20 places after decimal */
reply
posted by mohit_at_codepad on Apr 26
Integration sqrt(1-x^2) in limit[0-1] is also pi/4
(http://codepad.org/xtKNLR4P)
reply