50 likes | 125 Views
Chapter 7. Monte Carlo Methods to Compute Pi. Circle formed within a square, with unit radius so that square has sides 2*2. Ratio of the area of the circle to the square given by Points within square chosen randomly Score kept of how many points happen to lie within circle
E N D
Monte Carlo Methods to Compute Pi • Circle formed within a square, with unit radius so that square has sides 2*2. Ratio of the area of the circle to the square given by • Points within square chosen randomly • Score kept of how many points happen to lie within circle • Fraction of points within the circle will be pi/4, given a sufficient number of randomly selected samples
Monte Carlo Methods to Compute Pi #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char* argv[]) { double niter = 100000000; double x,y; int i; int count=0; double z; double pi; srand(time(NULL)); for (i=0; i<niter; ++i) { //get random points x = (double)random()/RAND_MAX; y = (double)random()/RAND_MAX; z = sqrt((x*x)+(y*y)); if (z<=1) { ++count; } } pi = ((double)count/(double)niter)*4.0; printf("Pi: %f\n", pi); }
Monte Carlo Methods to Compute Pi feng.gu@service0:~/csc229> ./pi Pi: 3.141370