7. Rectangle rule integration

The following equation shows the total area of the rectangles used to approximate the function's area:

Here the sum is over N slices. The value F(xi) gives the length of the i-th rectangle's left side. The value (xi+1 – xi) is the width of that rectangle.

If all of the rectangles have the same width, dx, then you can factor out that value from each term in the sum to give the following slightly simpler equation:

The following code calculates this sum:

// Use the rectangle rule to find the area under the curve.
private double RectangleRuleIntegrate(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;
for (int i = 0; i < numSlices; i++)
{
// Add the height at x.
total += F(x);
x += dx;
}
return total * dx;
}

The code sets dx to the width of the rectangles. It then loops through the rectangles, adding the height of the function at each rectangle's left edge and incrementing the x value by dx to move to the next slice.

After it adds up all of the rectangles' heights, the method multiplies the total by dx and returns the result.

The following screenshot shows the RectangleRuleIntegration example solution estimating the area under the same curve shown in the preceding screenshot:

If you look closely at the earlier screenshot, you'll see that Monte Carlo integration used 1,000 random points to estimate the area with an error of roughly 0.9. The new program uses only 10 rectangles to estimate the area with an error of only -0.05.

Download the RectangleRuleIntegration example solution to see additional details.

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

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