[ create a new paste ] login | about

Link: http://codepad.org/jTETyeAK    [ raw code | output | fork | 1 comment ]

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

const int NUM_ITER= 8 * 1000 * 1000;
const int RADIUS  = 16384;

int main() {
  const int SQRADIUS= RADIUS * RADIUS;
  int numHits = 0;
  int i = 0;
  srand(0);
  for(i = 0; i < NUM_ITER; ++i) {
    int x = 0, y= 0;
    x = rand() & (RADIUS-1);
    y = rand() & (RADIUS-1);
    x *= x;
    y *= y;
    numHits += (x + y < SQRADIUS) + (x + y <= SQRADIUS);
  }
  printf("Value of pi is: %g\n", 2.0 * numHits / NUM_ITER);
  return 0;
}


Output:
1
Value of pi is: 3.1419


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Apr 25
- Law of big number says, as NUM_ITER increases (approaches infinity), output number reaches pi.
- Radius must be a power of 2.
- Here I took a quarter circle of radius RADIUS centered around zero. and a square of side RADIUS bounding the quarter circle. Now I took NUM_ITER random points inside square. If the point is inside circle, I increase count by 2. If it is on the circle, increase the count by 1. The ratio of area of quarter circle and square is pi/4.
reply