/* This program approximates Pi by picking a points in a sqaure and * * and determining how often they are also in an appropriate circle. */ #include /* libraries for the pseudo-random number generator */ #include #include /* function prototypes */ /* generate a point in the square and determine if it is in the circle * parameter max_rand: the maximum size of a random number, as a double * return: 1 if the generated point is in the circle 0 if not */ int gen_and_check_point (double max_rane); /* perform simulation for many trials * parameter numTrials: number of points to be considered * return: number of generated points in circle */ int conduct_trials (int numTrials, double maxRandReal); /* global variables */ int MaxRandDouble = (double) RAND_MAX; int NumberOfTrials = 10000; int main () { /* initialize pseudo-random number generator */ printf ("This program approximates Pi by picking %d points in a square\n", NumberOfTrials); printf ("and counting the number in an appropriate circle.\n\n"); // initialize random number generator, based on the time of day srand (time ((time_t *) 0) ); printf ("RAND_MAX: %d\n", RAND_MAX); /* conduct simulation */ double number_in = conduct_trials (NumberOfTrials, MaxRandDouble); double pi_approx = 4.0 * number_in / NumberOfTrials ; /* report results */ printf ("The approximate value of Pi is %.5lf .\n", pi_approx); return 0; } /* full function bodies */ /* generate a point in the square and determine if it is in the circle * parameter maxReal: the maximum size of a random number, as a double * return: 1 if the generated point is in the circle 0 if not */ int gen_and_check_point (double max_rand) { double x, y; x = 2.0 * rand() / max_rand; y = 2.0 * rand() / max_rand; return (x*x + y*y <= 2.0*2.0); } /* perform simulation for many trials * parameter numTrials: number of points to be considered * return: number of generated points in circle */ int conduct_trials (int numTrials, double maxRandReal) { int i; int counter = 0; // pick points in first quadrant with coordinates between 0 and 1 // determine how many are in the circle of radius 1 for (i = 1; i <= NumberOfTrials; i++) { if (gen_and_check_point (maxRandReal)) counter++; } return counter; }