/* * Program to estimate pi using numerical integration. * * Also illustrates looping until convergence. */ #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) double curve(double x); double estimate(long num_slices); int main(void) { long num_slices; double threshold; printf("how many slices to start with?\n"); if ((scanf("%ld", &num_slices) != 1) || (num_slices <= 0)){ printf("not a positive integer\n"); return 1; } printf("convergence threshold?\n"); if ((scanf("%lf", &threshold) != 1) || (threshold <= 0)){ printf("not a positive number\n"); } double est = 1.0; double previous_est = 0.0; while (fabs(previous_est - est) > threshold) { /* save current estimate */ previous_est = est; /* compute new estimate and print */ est = estimate(num_slices); printf("result for %ld slices:\n%22.20f (differs from M_PI by %g)\n", num_slices, est, est - M_PI); /* double number of slices */ num_slices *= 2; } return 0; } double curve(double x) { return 4 / (1 + x*x) ; } double estimate(long num_slices) { double work = 0.0; /* sum of rectangle heights */ double width = 1.0/num_slices; for (int i = 0; i < num_slices; ++i) { work += curve(width*(i+0.5)); } return work * width; }