// ================================================================== // Author: Jean-Michel RICHER // Email: jean-michel.richer@univ-angers.fr // Institution: LERIA, Faculty of Science // University of Angers, France // ================================================================== // Compute integral of function f(x) = x^2 between X_0 and X_1 // using area of rectangles #include #include using namespace std; typedef double real; real X_0 = 1.0; real X_1 = 3.0; int STEPS = 1'000'000; /* ================================================================== * SUBPROGRAM * * real f(real x ; * * WHAT * * Function to integrate * * * PARAMETERS * * @paramdef(real, x) : abscissa * * ================================================================== */ real f( real x ) { return x * x; } /* ================================================================== * SUBPROGRAM * * real integrate(real x_0, real x_1, int steps) * * WHAT * * Use the sum of rectangles under the function * * HOW * * We compute the sum of (x_1 - x_0) / steps rectangles * * PARAMETERS * * @paramdef(real, x_0) : lower bound * @paramdef(real, x_1) : upper bound * @paramdef(int, steps) : number of rectangles to use * * RETURN VALUE * * @return(real) the sum of all rectangles that compose the * integral * * ================================================================== */ real integrate(real x_0, real x_1, int steps) { real dx, local; real delta_x = (x_1 - x_0) / steps; real area = 0; for (int i = 1; i <= steps; ++i) { area += f(x_0 + i * delta_x); } return delta_x * area; } /* ================================================================== * SUBPROGRAM * * int main(int argc, char *argv[]) * * WHAT * * Main program * * PARAMETERS * * @paramdef(int,argc) : number of command line arguments * @paramdef(char **, argv) : command line arguments as C-strings * * ================================================================== */ int main() { cout << "integrate(" << X_0 << ", " << X_1 << ")=" << integrate(X_0, X_1, STEPS) << endl; return EXIT_SUCCESS; }