/* * Program to approximate pi using numerical integration. */ #include #include #include #define M_PI acos(-1.0) double pi_approx(long nsamples, long seed); int main(void) { long seed; long num_samples; printf("enter seed, number of samples\n"); if (scanf("%ld %ld", &seed, &num_samples) != 2) { printf("not number\n"); return 1; } double pi = pi_approx(num_samples, seed); printf("with %ld samples approximation is %17.15f\n", num_samples, pi); printf("difference from best available constant %g\n", fabs(pi - M_PI)); return 0; } double pi_approx(long nsamples, long seed) { srand(seed); long count = 0; /* compute areas of rectangles and add */ for ( int i = 0; i < nsamples; ++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) nsamples); }