Area Under a Curve with Trapezoids
Intuition
To estimate the area under a curve, slice it into thin vertical strips and approximate each strip by a trapezoid (straight top). More strips → better fit.
Precise explanation
Split into equal pieces of width with points .
The ends get weight ½ because each interior point is shared by two trapezoids. The error shrinks roughly like : doubling cuts the error by about 4. The rule is exact for straight lines. If , the formula naturally gives a negative value, matching .
Figure (original): four trapezoids approximating the area under the red curve.
Worked example
. With , : . With : . Errors 0.0417 → 0.0104 (≈4× smaller).
Common mistakes
- Giving the endpoints weight 1.
- Using
range(n)and missing . - Computing by repeated addition (
x += h) — rounding drift; usea + i*h.
Why this matters
Numerical integration computes probabilities from densities, areas under ROC curves, and the path integral in integrated gradients (XA-14).
Library implementation
NumPy implements the same rule for sampled data as np.trapezoid(y, x) (named np.trapz before
NumPy 2.0), and SciPy offers more accurate methods such as scipy.integrate.quad. You will meet
NumPy in NP-01; the comparison below evaluates your function and NumPy's on the same grid.
References
- Mathematics for Machine Learning — Marc Peter Deisenroth, A. Aldo Faisal, Cheng Soon Ong (Cambridge University Press) (
S009) - Dive into Deep Learning — Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola (
S013)