Approximate definite integrals using the midpoint Riemann sum. Visualize rectangles, analyze error, and compare with exact values.
The Midpoint Rule is a numerical integration technique that approximates the definite integral ∫ab f(x) dx by summing the areas of rectangles whose heights are determined by the function value at the midpoint of each subinterval. For n equal subintervals of width Δx = (b-a)/n, the approximation is:
Mn = Δx · [ f(m1) + f(m2) + ... + f(mn) ]
where mi = a + (i - 0.5)Δx is the midpoint of the i-th subinterval.
The midpoint rule often provides better accuracy than the left or right Riemann sums for the same number of intervals because it balances over- and under-estimates. Its error bound is proportional to the second derivative of f: |E| ≤ K(b-a)³/(24n²), where K = max|f''(x)| on [a,b].
1. Input validation: The function is parsed safely using the JavaScript Function constructor.
2. Discretization: Subinterval width Δx = (b-a)/n, midpoints xi* = a + (i-0.5)Δx.
3. Summation: Compute f(mi) for each midpoint, multiply by Δx, and sum.
4. Visualization: The canvas draws the function curve, each rectangle from the x-axis to f(mi) with semi-transparent fill, and marks midpoints.
The algorithm runs entirely client-side, offering instant feedback. For differentiable functions with bounded second derivative, the error decreases as O(1/n²).
| Function & Interval | Exact Integral | Midpoint (n=4) | Error (n=4) | Midpoint (n=10) |
|---|---|---|---|---|
| f(x)=x², [0,2] | 8/3 ≈ 2.6666667 | 2.65625 | 0.0104167 | 2.66333 |
| f(x)=sin(x), [0,π] | 2.0 | 2.008248 | 0.008248 | 2.00083 |
| f(x)=eˣ, [0,1] | e-1 ≈ 1.7182818 | 1.71475 | 0.00353 | 1.71757 |
| f(x)=2x+1, [0,3] | 12.0 | 12.0 | 0.0 (linear) | 12.0 |
In physics, the work done by a variable force F(x) along a displacement from a to b is given by ∫ab F(x) dx. For non-linear forces (e.g., spring with varying stiffness), the midpoint rule gives a quick estimate. Example: F(x)=100·sin(x) from 0 to π. The calculator yields ≈ 200.0 Joules, matching the exact analytical result and confirming reliability.