I thought of an algorithm for integral calculation that should be more accurate that the regular rectangle approach. My algorithm can be best described with a graphic (I am using f(x) = sin(x) as example):
First the x and y positions of the points P1, P2, P3, P4 are calculated (red dots).
The area of the green four sided figure is a part of the result. This area is calculated by dividing it into two triangles (blue line).
The area of each triangle is calculated using the Heron’s formula.
I think it is obvious that this should lead to much better results than the rectangle approach.
In code this looks like this:
double integral(double f(double x), double min, double max) {
Point p1, p2, p3, p4;
double area = 0.0;
double s1 = 0.0;
double s2 = 0.0;
for(double x = min; x < max; x += stepSize) {
p1.x = x;
p1.y = 0.0;
p2.x = x;
p2.y = f(x);
p3.x = x + stepSize;
p3.y = f(x + stepSize);
p4.x = x + stepSize;
p4.y = 0.0;
s1 = 0.5 * (distance(p1, p2) + distance(p2, p4) + distance(p1, p4));
s2 = 0.5 * (distance(p2, p3) + distance(p3, p4) + distance(p2, p4));
area += sqrt(s1 * (s1 - distance(p1, p2)) * (s1 - distance(p2, p4)) * (s1 - distance(p1, p4)));
area += sqrt(s2 * (s2 - distance(p2, p3)) * (s2 - distance(p3, p4)) * (s2 - distance(p2, p4)));
}
return area;
}
The distance
function is just returning the distance between two points in 2D space. The Point
struct is just holding a x and y coordinate. stepSize
is a constant that I set to 0.001
My function is giving a result that is correct, but I wanted to know how much more precise it is compared to the rectangle approach.
On the internet I found this code that is calculating a integral using rectangles:
double integral2(double(*f)(double x), double a, double b, int n) {
double step = (b - a) / n; // width of each small rectangle
double area = 0.0; // signed area
for (int i = 0; i < n; i ++) {
area += f(a + (i + 0.5) * step) * step; // sum up each small rectangle
}
return area;
}
I both tested them using the standard math.h
sin
function from 0.0 to half π. This area should be 1.
My algorithm has given me the result 1.000204
for a step-size of 0.001
.
The rectangle algorithm hast given me the result 1.000010
with a calculated step-size of 0.015708
.
How can such a difference in accuracy and step-size be explained? Did I implement my algorithm wrong?
Update
Using the calculated step-size of the second method, I get the result 0.999983
which is much closer to one than the result with a step-size of 0.001
.
Now how can that work??