I am attempting to approximate integrals using an adaptive Trapezoidal Rule.
I have a coarse integral approximation:
//Approximates the integral of f across the interval [a,b]
double coarse_app(double(*f)(double x), double a, double b) {
return (b - a) * (f(a) + f(b)) / 2.0;
}
I have a fine integral approximation:
//Approximates the integral of f across the interval [a,b]
double fine_app(double(*f)(double x), double a, double b) {
double m = (a + b) / 2.0;
return (b - a) / 4.0 * (f(a) + 2.0 * f(m) + f(b));
}
This is made adaptive by summing the approximation across decreasing portions of the given interval until either the recursion level is too high or the coarse and fine approximation are very close to one another:
//Adaptively approximates the integral of f across the interval [a,b] with
// tolerance tol.
double trap(double(*f)(double x), double a, double b, double tol) {
double q = fine_app(f, a, b);
double r = coarse_app(f, a, b);
if ((currentLevel >= minLevel) && (abs(q - r) <= 3.0 * tol)) {
return q;
} else if (currentLevel >= maxLevel) {
return q;
} else {
++currentLevel;
return (trap(f, a, b / 2.0, tol / 2.0) + trap(f, a + (b / 2.0), b, tol / 2.0));
}
}
If I manually calculate an integral by breaking it up into sections and using fine_app on it, I get a very good approximation. However, when I use the trap function, which should do this for me, all of my results are far too small.
For example, trap(square, 0, 2.0, 1.0e-2) gives the output 0.0424107, where the square function is defined as x^2. However, the output should be around 2.667. This is far worse than doing a single run of fine_app on the entire interval, which gives a value of 3.
Conceptually, I believe I have it implemented correctly, but there is something about C++ recursion which is not doing what I expect it to.
First time programming in C++, so all improvements are welcome.
I’m assuming you have currentLevel defined somewhere else. You don’t want to do that. You also calculate your midpoints incorrectly.
Take a = 3, b = 5:
The correct points should be [3, 4] and [4, 5]
The code should look like this:
You can add a helper function so you don’t have to specify currentLevel:
If I call this as
integrate(square, 0, 2, 0.01)I get the answer of 2.6875, which means you need an even lower tolerance to converge to the correct result of8/3 = 2.6666...7. You can check the exact error bound on this by using the error terms for Simpson’s method.