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 [a,b][a, b] into nn equal pieces of width h=(b−a)/nh = (b-a)/n with points xi=a+ihx_i = a + ih.

∫abf(x) dx≈h[12f(x0)+f(x1)+⋯+f(xn−1)+12f(xn)].\int_a^b f(x)\,dx \approx h\left[\tfrac12 f(x_0) + f(x_1) + \dots + f(x_{n-1}) + \tfrac12 f(x_n)\right].

The ends get weight ½ because each interior point is shared by two trapezoids. The error shrinks roughly like h2h^2: doubling nn cuts the error by about 4. The rule is exact for straight lines. If a>ba > b, the formula naturally gives a negative value, matching ∫ab=−∫ba\int_a^b = -\int_b^a.

Composite trapezoidal rule with n = 4 ab

Figure (original): four trapezoids approximating the area under the red curve.

Worked example

∫01x2dx=1/3\int_0^1 x^2 dx = 1/3. With n=2n=2, h=0.5h=0.5: 0.5[12⋅0+0.25+12⋅1]=0.3750.5[\tfrac12\cdot0 + 0.25 + \tfrac12\cdot1] = 0.375. With n=4n = 4: 0.343750.34375. Errors 0.0417 → 0.0104 (≈4× smaller).

Common mistakes

  • Giving the endpoints weight 1.
  • Using range(n) and missing xn=bx_n = b.
  • Computing xix_i by repeated addition (x += h) — rounding drift; use a + 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