/* * Program to estimate pi using numerical integration, revised to demonstrate * more-general routine to perform 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 curve1(double x); double curve2(double x); /* estimated area under curve specified by "fcn" from a to b */ double estimate(double a, double b, long num_slices, double (*fcn)(double x)); 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(0.0, 1.0, num_slices, curve1); printf("result for %ld slices:\n%22.20f (differs from M_PI by %g)\n", num_slices, pi_est, pi_est - M_PI); double tryit = estimate(10.0, 20.0, num_slices, curve2); printf("result of integrating x*x from 0 to 10, %ld slices:\n%22.20f\n", num_slices, tryit); return 0; } double curve1(double x) { return 4 / (1 + x*x) ; } double curve2(double x) { return x*x; } double estimate(double a, double b, long num_slices, double (*fcn)(double x)) { double work = 0.0; /* sum of rectangle heights */ double width = (b-a)/num_slices; for (int i = 0; i < num_slices; ++i) { work += fcn(a + width*(i+0.5)); } return work * width; }