Well, it's not a single equation. If it was, the result could be calculated in just one line of code.
We know the area of a rectangle is base * height
The area of a trapezoid is similar, but there are two heights (left and right edges), so we take the average. Thus area = (height1 + height2)/2 * base
Those are the basic building blocks. What we need to do is to add up the total area of several rectangles (or several trapezoids).
Let's take an example.
Assume the function is the first one, 5x^4 + 3x^3 - 10x + 2
Lets say the user has input
a = 1
b = 2
n = 3
(Ignore choice for now, we can come back to that later)
So we split the region between a and b into three (that is n) slices.
first trapezoid
The first one has
x_left = 1
x_right = 1.33333
The two heights are calculated by calling the function fx with these values of x.
height_left = 0
height_right = 11.58
base = 0.33333
area = (height_left + height_right) / 2 * base
=1.93
Now we add that value to the total area
second trapezoid
Now we repeat the process
x_left = 1.33333
x_right = 1.66667
height_left = 11.58
height_right = 37.80
base = 0.33333
area = (height_left + height_right) / 2 * base
=8.23
add that to the total area
third trapezoid
x_left = 1.66667
x_right = 2
height_left = 37.80
height_right = 86
base = 0.33333
area = (height_left + height_right) / 2 * base
=20.63
again, add that to the total area.
Result
The result in this case is 1.93 + 8.23 + 20.63 which is 30.79
The proper answer is 29.25, but remember this is just an approximation. Using a bigger value of n will give a better answer.
So, that's a description (probably a confusing one) of how to get the area using trapezoids.
How to turn it into code?
Well, start with a variable which will contain the total, set it to zero.
Calculate the width of each slice ("base" in my example above) as (b-a)/n
Then we need a loop. Usually a for loop.
Something like
1 2 3 4
|
for (int i=0; i<n; i++)
{
}
| |
Inside the loop we calculate the area of a single trapezoid and add it to the total.
When the loop finishes, the total area is the value to be returned from the function.