# include # include # include using namespace std; int main ( ) // // INTEGRAL estimates the integral of x*x+2*x-3, from -4 to 5, // using random sampling. // // The user enters the number of sample points to use. // { int i, n; double a = - 4.0, b = 5.0, error, estimate, x; double f ( double x ); double random_double_ab ( double a, double b ); double sum = 0.0; cout << "Enter number of points n for integral estimate: "; cin >> n; // // This call to srand() will scramble the random number generator // for us. // srand ( time ( ) ); for ( i = 1; i <= n; i++ ) { x = random_double_ab ( a, b ); sum = sum + f ( x ); } estimate = ( b - a ) * sum / ( double ) n; error = fabs ( estimate - 45.0 ); cout << "Integral estimate using " << n << " points is " << estimate << "\n"; cout << "Error is " << error << "\n"; return 0; } double f ( double x ) { double value; value = x * x + 2 * x - 3; return value; } double random_double_ab ( double a, double b ) { double r; double value; r = ( double ) rand ( ) / ( double ) RAND_MAX; value = a + ( b - a ) * r; return value; }