/* * Program to approximate pi using Monte Carlo approach: * * Simulate throwing darts at board with quarter-circle * inscribed in unit square, counting how many fall within * the quarter-circle. The ratio of this count to the total * number of darts should be approximately the same as the * ratio of the area of the quarter-circle to the area of * the square -- i.e., pi/4. * * (In the code, "samples" is the number of darts.) */ #include #include #include double estimate_pi(int seed, int samples); int main(int argc, char * argv[]) { if (argc < 3) { printf("usage: %s num_samples seed\n", argv[0]); return EXIT_FAILURE; } char *endptr; long samples = strtol(argv[1], &endptr, 10); if ((*endptr != '\0') || samples <= 0) { printf("invalid num_samples\n"); return EXIT_FAILURE; } long seed = strtol(argv[2], &endptr, 10); if ((*endptr != '\0') || seed <= 0) { printf("invalid seed\n"); return EXIT_FAILURE; } double pi = estimate_pi(seed, samples); printf("%ld samples, seed %ld, result %.15f, difference %.15f\n", samples, seed, pi, fabs(pi-acos(-1.0))); return EXIT_SUCCESS; } double estimate_pi(int seed, int samples) { srand(seed); int count = 0; /* "throw" darts and count how many are inside the circle */ for (int i = 0; i < samples; ++i) { double x = ((double) rand()) / ((double) RAND_MAX); double y = ((double) rand()) / ((double) RAND_MAX); if ((x*x + y*y) <= 1.0) { count += 1; } } return 4 * ((double) count) / ((double) samples); }