/* * Program to approximate multiple functions using numerical integration. */ #include #include /* * function to perform numerical integration * last parameter is function to integrate */ double approx(long nslices, double start, double end, double (*fcn) (double x)); /* * some functions to try */ /* function we used to approximate pi */ double fcn_for_pi(double x) { return 4.0 / (1 + x*x); } /* straight line -- y=2 */ double fcn_line(double x) { return 2; } /* straight line -- y=x*2 */ double fcn_line2(double x) { return x * 2; } /* main program */ int main(void) { long num_slices; printf("enter number of slices\n"); if (scanf("%ld", &num_slices) != 1) { printf("not number\n"); return 1; } /* call approx function several times to integrate various functions */ printf("with %ld slices approx pi is %.15f\n", num_slices, approx(num_slices, 0.0, 1.0, fcn_for_pi)); printf("with %ld slices approx integral of constant line is %.15f\n", num_slices, approx(num_slices, 1.0, 5.0, fcn_line)); printf("with %ld slices approx integral of sloped line is %.15f\n", num_slices, approx(num_slices, 1.0, 5.0, fcn_line2)); return 0; } double approx(long nslices, double start, double end, double (*fcn) (double x)) { double width = (end - start) / nslices; double sum = 0.0; /* compute heights of rectangles and add */ for ( int i = 0; i < nslices; ++i) { double mid = start + i*width + 0.5*width; double f_at_mid = fcn(mid); sum += f_at_mid; } /* area is sum of heights times width */ return sum * width; }