/* * Program to estimate pi using "Monte Carlo" method: * * Simulates throwing darts at a dartboard with a quarter circle and * counting how many are inside the (quarter) circle. */ #include #include #include /* best(?) available value of pi, to check computed approximation */ /* surprisingly, no library-defined constant for this in standard C! */ #define M_PI acos(-1.0) int main(void) { long samples; int seed; printf("samples, seed?\n"); if (scanf("%ld %d", &samples, &seed) != 2) { printf("values not integers\n"); return 1; } srand(seed); long in_circle = 0; /* simulate throwing darts at a dartboard with a quarter-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) { in_circle += 1; } } double est_pi = 4 * (double) in_circle / samples; printf("result for %ld samples and seed %d:\n%22.20f (differs from M_PI by %g)\n", samples, seed, est_pi, est_pi - M_PI); return 0; }