/* * Program to estimate pi using numerical integration. */ #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; printf("how many slices?\n"); if ((scanf("%ld", &num_slices) != 1) || (num_slices <= 0)){ printf("not a positive integer\n"); return 1; } double pi_est = estimate(num_slices); printf("result for %ld slices:\n%22.20f (differs from M_PI by %g)\n", num_slices, pi_est, pi_est - M_PI); 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; }