> cat integral1.C // file integral1.C, cs2223, D97/98 // // random programming integration // 14Apr98 NW, First version // includes #include "headers.h" // definitions #define NMAX 10000000 // prototype float integrate (int, float, float, float, double (*) (double)); // random integration // main() int main () { srand(time(NULL)); // seed the random number generator float pi = 4.0 * atan(1.0); float a = 0, b = pi/2, c = 1.0; for (int n = 1; n <= NMAX; n *= 10) { cout << "when n = " << n << " the integral = " << integrate(n,a,b,c,&sin) << endl; } return 0; } // end main() float integrate(int n_points, float a, float b, float c, double (*fun) (double)) { int counter = 0; float ratio = c * (b - a) / (float) n_points; while (n_points--) { float x = a + (b - a) * ((float) rand() / (float) RAND_MAX); float y = c * ((float) rand() / (float) RAND_MAX); if (y <= fun(x)) counter++; } return (float) counter * ratio; } // end integrate() // Copyright 1998 Norman Wittels > g++ integral1.C > a.out when n = 1 the integral = 1.5708 when n = 10 the integral = 0.942478 when n = 100 the integral = 0.989602 when n = 1000 the integral = 1.00688 when n = 10000 the integral = 0.994942 when n = 100000 the integral = 0.995869 when n = 1000000 the integral = 1.00066 when n = 10000000 the integral = 0.999986