8. Trapezoid rule integration

A trapezoid is a quadrilateral (four-sided polygon) that has two parallel sides. The parallel sides are called its bases and the other two sides are called its legs. The trapezoid's height is the distance between the two bases.

If a trapezoid has a height of h and base lengths b1 and b2, then its area is h × (b1 + b2) / 2. The following equation gives the sums of the areas used to approximate the area under a function:

If we assume that all of the trapezoids have the same height, dx = (xi+1 – xi), then we can factor out the dx and the factor of ½ to get the following:

This is simple, but we can make it even simpler if we notice that most of the x values appear twice in the sum, once as an xi term and once as an xi+1 term. The exceptions are the first (leftmost) and last (rightmost) values, x0 and xN, which each appear only once. Using that observation, we can rewrite the equation to get the following version:

Finally, we can rearrange this slightly to get the following:

The following code calculates this value:

// Use the rectangle rule to find the area under the curve.
private double TrapezoidRuleIntegrate(Func<double, double> F,
double xmin, double xmax, double ymin, double ymax, int numSlices)
{
double total = 0;
double dx = (xmax - xmin) / numSlices;
double x = xmin + dx;
for (int i = 1; i < numSlices; i++)
{
// Add the height at x.
total += F(x);
x += dx;
}
total = total + (F(xmax) + F(xmin)) / 2;
return total * dx;
}

This code calculates dx and then uses a loop to add up the x values, except for the first and last values. After the loop, it adds the first and last values divided by two. Finally, it multiples that sum by dx and returns the result.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.111.203