Comparing Methods of Riemann Sums in Python

The Riemann Sum of the region under a continuous function can be used to define the integration of that function. In studying integral calculus, it helps to compare the ways that the sum of rectangles or trapezoids in approximating the integral of such a function. To make this easier to visualise, the Python library Matplotlib provides adequate tools for presenting such a comparision of Riemann Sum operations, whether using rectangles or trapezoids. Here, I show a simple demo of both the sum of rectangles as well as the sum of trapezoids to compare these approximations to the "exact" area as calculated by the integrate.quad function of the Python library Scipy.

This demo also includes a DiscreteSlider class as Joe Kington provided in a thread at Stackoverflow (many thanks to Joe for sharing this).

One can download the source code for this demo at http://github.com/mikequentel/area_curve or http://downloads.mikequentel.com/areacurve.py.tar.gz

The demo uses a slider control to change the number of panels (rectangles and trapezoids) to change the resolution of the approximation of the area under a curve. As the number of panels increases, the width of each panel decreases, thus increasing the resolution; one can see the resolution slowly approach the "exact" area calculated whilst sliding the control to the right. The rectangular area ("Mid Sum Area") is calculated using the midpoint method; the trapezoid area ("Trap Sum Area") is calculated using trapezoids at the same x boundaries.

No comments: