/* * Program to approximate pi using Monte Carlo approach: * Simulate throwing darts at board with quarter-circle * inscribed in unit square. */ #include #include double estimate_pi(int seed, int darts); int main(void) { int seed; int darts; printf("enter seed, number of darts\n"); if (scanf("%d %d", &seed, &darts) != 2) { printf("not numbers\n"); return 1; } double pi = estimate_pi(seed, darts); printf("with %d darts approximation is %.15f\n", darts, pi); return 0; } double estimate_pi(int seed, int darts) { srand(seed); int count = 0; /* "throw" darts and count how many are inside the circle */ for (int i = 0; i < darts; ++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) darts); }