#include using namespace std; //We first define two simple functions for testing with our integrator: // f1(x) = x^2 double function1(double x) { return x*x; } //and f2(x) = x double function2(double x) { return x; } //This is our function which accepts another function as an argument. Note //the syntax of the first argument, in particular. //Note also this uses the simple left endpoint approximation to the integral. double integral( double function_to_use(double), double x_l, double x_r, int nsteps) { double step_size = (x_r - x_l) / double(nsteps); double running_sum = 0; for (int i = 0; i < nsteps - 1; ++i) { double this_x = x_l + step_size * double(i); double this_value = function_to_use(this_x) * step_size; running_sum += this_value; } return running_sum; } main() { int nsteps; cout << "Choose nsteps: "; cin >> nsteps; //The first call to integral uses function1, x^2, as the argument. double this_integral = integral(function1,-1,1,nsteps); double true_integral = 2./3.; cout << "Integral of x^2 from -1 to 1 is: "; cout << this_integral << endl; cout << "This corresponds to an error of: " << this_integral - true_integral << endl; //The second uses function2, x this_integral = integral(function2,-1,1,nsteps); true_integral = 0.; cout << "Integral of x from -1 to 1 is: "; cout << this_integral << endl; cout << "This corresponds to an error of: " << this_integral - true_integral << endl; }