/* ------------------------------------------------------------------- // Figure 14.24: A Monte Carlo approximation. // Figure 14.26: Functions for the Monte Carlo simulation. // ------------------------------------------------------------------- */ #include "tools.h" #define BOX_SIDE 2.0 /* Length of side of bounding box. */ typedef struct POINT { double x, y; } point_type ; bool inside( point_type p ); double simulate( int max, double box_side ); void main( void ) { double area; /* Approximate area of unit circle. */ int trials; /* Loop limit. */ banner(); puts( " Monte Carlo Approximation to Area of a Unit Circle" ); srand( (unsigned)time( NULL ) ); /* seed random number generator */ printf( " Number of random trials to use = " ); scanf( "%i", &trials ); area = simulate( trials, BOX_SIDE ); printf( " With %i trials, estimate of circle area = %.4g\n", trials, area ); bye(); } /* Is point p inside a unit circle? --------------------------------------- */ bool inside( point_type p ) { return sqrt( p.x * p.x + p.y * p.y ) < 1.0; } /* Carry out the random trials -------------------------------------------- */ double simulate( int max, double box_side ) { point_type random; /* The point we select. */ int k; /* Loop counter. */ int count = 0; /* Number of successful trials. */ for (k = 0; k < max; ++k) { /* Get random x and y coordinates for point. */ random.x = (randy() -.5) * box_side; random.y = (randy() -.5) * box_side; if (inside( random )) count += 1; /* +1 if inside circle. */ } return box_side * box_side * ((double)count / max); }