/* * C program to compute the value of pi using Monte Carlo * * command-line arguments: number_of_samples, seed */ #include #include #include /* has M_PI, fabs() */ #include "timer.h" /* has get_time() */ /* main program */ int main(int argc, char* argv[]) { int num_samples; int seed; double start_time, end_time; int count = 0; double x, y; int i; double pi; /* process command-line arguments */ if (argc != 3) { fprintf(stderr, "usage: %s number_of_samples seed\n", argv[0]); exit(EXIT_FAILURE); } num_samples = atoi(argv[1]); seed = atoi(argv[2]); if ((num_samples <= 0) || (seed <= 0)) { fprintf(stderr, "usage: %s number_of_samples seed\n", argv[0]); exit(EXIT_FAILURE); } /* record start time */ start_time = get_time(); /* do calculation */ srandom((unsigned int) seed); for (i = 0; i < num_samples; ++i) { x = (double) random() / (double) (RAND_MAX); y = (double) random() / (double) (RAND_MAX); if ((x*x + y*y) <= 1.0) ++count; } pi = 4.0 * (double) count / (double) num_samples; /* record end time and print results */ end_time = get_time(); printf("sequential C program results:\n"); printf("number of samples = %d, seed = %d\n", num_samples, seed); printf("estimated pi = %12.10f\n", pi); printf("difference between estimated pi and math.h M_PI = %12.10f\n", fabs(pi - M_PI)); printf("time to compute = %g seconds\n", end_time - start_time); /* clean up and return */ return EXIT_SUCCESS; }