7.4 Definite Integrals: Trapezoid and Simpson
Once you train classifiers, such as the BERT and ELECTRA heads in ELECTRA: replaced-token detection and Fine-tuning heads and the linear-head export in AI Engineering, or the usage-policy head a serving gateway runs, you need to know how good a score is at separating two classes. The standard answer that does not depend on any one threshold is the area under the ROC curve, computed in Logistic regression, ROC-AUC, and calibration. That curve is not a formula. It is a list of corner points, one per threshold, and its area is a definite integral over samples. The same integral computes the reliability-curve area in a safety report.
Concepts from other sections (4)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- ROC curve: the staircase of (FPR, TPR) pairs traced as the decision threshold falls through every distinct score. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- AUC: the area under the ROC curve, equal to the probability that a random positive outscores a random negative, ties counting half. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- Richardson extrapolation: combining differences at with weights to cancel successive even powers of . Read more: 7.1 Derivatives and Finite Differences
- central difference: , a second-order approximation of . Read more: 7.1 Derivatives and Finite Differences
Get the integration rule subtly wrong, by counting each step at its left height or by sorting points that were deliberately ordered, and every AUC you report is biased, with nothing visibly broken. This section builds the area rule for samples and, for functions you can evaluate anywhere, the two classic rules with predictable errors: the trapezoid rule and Simpson’s rule. The finished code is course/solutions/python/tinyllm/num/integrate.py, with trapezoid, trapezoid_rule, and simpson (and the helpers _samples and _nodes); the contract is course/contracts/py/tinyllm/num/integrate.pyi.
There is nothing to call from earlier sections, but the error analysis reuses the Taylor expansion and Richardson extrapolation from Derivatives and finite differences.
Learning objectives
- Define the definite integral as a limit of Riemann sums and use the fundamental theorem of calculus to evaluate one exactly.
- Derive the composite trapezoid and Simpson rules and state their error orders.
- Explain why Simpson’s rule is exact on cubics and why it is Richardson extrapolation of the trapezoid rule.
- Integrate unevenly spaced samples with signed widths, without sorting.
- Implement the three integrators with validation that keeps NaN areas from escaping.
The definite integral
Section titled “The definite integral”Cut into slices of width , stand a rectangle on each slice with the height of somewhere in it, and add the areas: . This is a Riemann sum. As the sums for a continuous settle on one number whatever points you chose, and that number is the definite integral . Area below the axis counts as negative, which is why it is a signed area. Running from to makes every width , so , and an interval of length 0 has integral 0. A computer stops at slices.
The fundamental theorem of calculus links this area to derivatives: if is an antiderivative of , meaning , then . For , , so . Most integrals met in practice have no in closed form (, the shape of the normal density, is the famous one), or is known only at sample points. Then the area is computed numerically, which is called quadrature.
The trapezoid
Section titled “The trapezoid”In what follows, is the number of equal steps, is the step, for are the nodes (numpy.linspace(a, b, n + 1)), and . Replace on one step by the straight line through its two end values. The region under that line is a trapezoid with parallel sides and and width , so its area is : the width times the average height. A straight line is integrated exactly, because the “approximation” is the function itself.
The composite rules
Section titled “The composite rules”Add one trapezoid per step. Every inner node belongs to two trapezoids and is counted twice at half weight; the two end nodes belong to one each. The composite trapezoid value with step is
Simpson’s rule instead takes the steps in pairs and fits the parabola through the three points at . The area under that parabola, over a panel of width , is ; to check it, integrate the parabola through term by term. Adding the panels, every even inner node is shared by two panels:
The pattern 1, 4, 2, 4, …, 2, 4, 1 closes only when is even. An odd is not a smaller Simpson’s rule; it is a different, wrong one, so the contract raises instead of rounding.
Integrating samples
Section titled “Integrating samples”An ROC curve is a list of points with uneven gaps, produced by sweeping a threshold. Its area is the trapezoid rule applied step by step with each step’s own width: . The widths keep their sign, so the order of the points is the direction of travel: the same points in decreasing order give the negative area, exactly as running an integral from to . The function never sorts, because sorting would silently reconnect the points in a different order; the curve the caller drew is the curve that gets measured. Fewer than two points enclose nothing, so the area is 0.
You now have three rules. The next question is how wrong each one is.
Error and order
Section titled “Error and order”Expand around the middle of one step with Taylor’s formula, which Taylor series proves. The straight line misses the curvature term, and integrating the difference over one step gives an error of for some in the step. There are steps, so the composite errors are
The trapezoid rule is second order: halve and the error drops by 4. Simpson is fourth order: halve and it drops by 16. A parabola should only be exact on quadratics, yet the error involves , so Simpson is exact on cubics too: the error on the left half of a panel cancels the one on the right half by symmetry. The table shows both rules on :
| 2 | 4 | 8 | 16 | 32 | |
|---|---|---|---|---|---|
| trapezoid error | |||||
| Simpson error |
Each column divides the trapezoid error by 4 and the Simpson error by 16: log-log slopes of 2 and 4. The error formulas assume is smooth at the scale of . On Runge’s peak over with , Simpson’s error is 0.026 and the trapezoid’s 0.0075: the parabolas overshoot a peak that is narrower than two steps. Higher order pays off only once resolves the function.
Simpson is Richardson
Section titled “Simpson is Richardson”The trapezoid error is not just ; it is a series in even powers, , where is the exact integral (this is the Euler-Maclaurin formula). That is the same shape as the central difference’s error series, so the same Richardson step removes the leading term:
Write it out node by node and the weights come out as 1, 4, 2, 4, …, 1 over 3: it is Simpson’s rule on the finer grid. Repeating the step (weights ) is Romberg integration. The solution’s simpson and trapezoid_rule satisfy this identity to rounding.
Working it by hand
Section titled “Working it by hand”Take and apply each rule:
| Rule | Nodes and values | Computation | Value | Error |
|---|---|---|---|---|
| , , | 5 | 1 | ||
| , , | 4.25 | 0.25 | ||
| , , | 4 | 0 | ||
| Richardson | , | 4 | 0 |
Halving divided the trapezoid error by exactly 4 (here and the error formula is exact up to the mean value). Simpson is exact because is a cubic, and Richardson’s combination of the two trapezoid values gives the same 4.
Now take three samples, the corners of an ROC curve: , , . The two trapezoids have areas and , for a total of 0.625. Counting each step at its left height only (a left Riemann sum) gives .
Designing the interface
Section titled “Designing the interface”There is one sample integrator and two function integrators:
def trapezoid(y: ArrayLike, x: ArrayLike) -> float: ...def trapezoid_rule(f: Callable[[NDArray], NDArray], a: float, b: float, n: int) -> float: ...def simpson(f: Callable[[NDArray], NDArray], a: float, b: float, n: int) -> float: ...trapezoid integrates samples in the order given, like numpy’s trapezoid(y, x). The two rules take a function vectorized over float64 arrays and evaluate it once on numpy.linspace(a, b, n + 1), so both end nodes are exact and every implementation agrees with scipy to the last bit; is allowed. All three return a Python float and raise ValueError for non-finite input, mismatched samples, a wrongly shaped or non-finite f, n < 1, or (for Simpson) an odd n.
Building it step by step
Section titled “Building it step by step”Seven decisions produce the solution.
- For samples, use one trapezoid per step with its signed width. Step contributes . In array form that is
np.diff(x) * (y[:-1] + y[1:]), summed, divided by 2. Nothing is sorted and no absolute value is taken, so the given order is the direction of travel. - Give fewer than two samples no area. With 0 or 1 points there are no steps; return 0.0 rather than indexing an empty difference.
- For functions, evaluate once on fixed nodes. The nodes are
np.linspace(a, b, n + 1): steps need nodes, andlinspaceputs the first and last exactly at and . One vectorized call tofreturns all , which keeps every implementation of the contract (Python, C, scipy) on the same nodes and so on the same rounding. - Let the step carry the direction. is negative when and zero when , so the composite formulas give and with no special cases.
- Apply the trapezoid weights. The end nodes get , inner nodes 1, all times .
- Apply the Simpson weights. times . Odd-indexed nodes are the parabola midpoints (weight 4), even inner nodes are shared by two panels (weight 2). This closes only for even , so odd raises.
- Validate everything that could make the area meaningless. Non-finite limits or samples, mismatched lengths, an
fthat returns the wrong shape or a non-finite value, and badnall raiseValueErrorrather than producing a NaN area.
The sample rule comes with its validator:
def _samples(y: ArrayLike, x: ArrayLike) -> tuple[NDArray, NDArray]: ya = np.asarray(y, dtype=np.float64) xa = np.asarray(x, dtype=np.float64) if ya.ndim != 1 or xa.ndim != 1: # a curve is a 1-D list of points raise ValueError(f"x and y must be 1-D, got shapes {xa.shape} and {ya.shape}") if ya.shape != xa.shape: # every height needs its abscissa raise ValueError( f"x and y must have the same length, got {xa.size} and {ya.size}" ) if not (np.all(np.isfinite(ya)) and np.all(np.isfinite(xa))): raise ValueError("x and y must be finite") return ya, xa
def trapezoid(y: ArrayLike, x: ArrayLike) -> float: ya, xa = _samples(y, x) if ya.size < 2: return 0.0 # no step, no area # One trapezoid per step: width times the mean of its two heights. The # widths keep their sign, so the order of the samples is the direction. return float(np.sum(np.diff(xa) * (ya[:-1] + ya[1:])) / 2.0)On the ROC corners, np.diff(xa) is and ya[:-1] + ya[1:] is ; the products sum to , and halving gives . Note the argument order, y first, as in numpy and in the trapezoid(tpr, fpr) call that computes ROC-AUC.
The two function rules share node construction and checking:
def _nodes( f: Callable[[NDArray], NDArray], a: float, b: float, n: int) -> tuple[NDArray, float]: a, b = float(a), float(b) if not (math.isfinite(a) and math.isfinite(b)): raise ValueError(f"a and b must be finite, got {a} and {b}") xs = np.linspace(a, b, n + 1) # n steps, n + 1 nodes, ends exact fx = np.asarray(f(xs), dtype=np.float64) # one vectorized call if fx.shape != xs.shape: raise ValueError(f"f must return shape {xs.shape}, got {fx.shape}") if not np.all(np.isfinite(fx)): raise ValueError("f returned a non-finite value on the nodes") return fx, (b - a) / n # h is signed: negative when b < a
def _steps(n: int) -> int: if int(n) != n: # 4.0 is fine, 4.5 is not raise ValueError(f"n must be an integer, got {n!r}") return int(n)
def trapezoid_rule( f: Callable[[NDArray], NDArray], a: float, b: float, n: int) -> float: n = _steps(n) if n < 1: raise ValueError(f"n must be >= 1, got {n}") fx, h = _nodes(f, a, b, n) # The two ends belong to one trapezoid each, every inner node to two. return float(h * (fx[0] / 2.0 + np.sum(fx[1:-1]) + fx[-1] / 2.0))
def simpson(f: Callable[[NDArray], NDArray], a: float, b: float, n: int) -> float: n = _steps(n) if n < 2 or n % 2 != 0: raise ValueError(f"Simpson needs an even number of steps n >= 2, got {n}") fx, h = _nodes(f, a, b, n) # Weights 1, 4, 2, 4, ..., 2, 4, 1: odd nodes are parabola midpoints, # even inner nodes are shared by two parabolas. odd = np.sum(fx[1:-1:2]) # indices 1, 3, ..., n - 1 even = np.sum(fx[2:-1:2]) # indices 2, 4, ..., n - 2 (empty when n = 2) return float(h / 3.0 * (fx[0] + 4.0 * odd + 2.0 * even + fx[-1]))On with , the nodes are , fx is , odd is 1, even is the empty sum 0, and the result is . With trapezoid_rule and : . The Richardson identity holds node by node: gives times , and dividing by 3 is exactly the simpson expression. The full solution is in integrate.py.
Why this design
Section titled “Why this design”All three functions are in time and memory: one pass of np.diff and a sum for samples, and one call to f on nodes for the rules. To reach an error the trapezoid rule needs nodes and Simpson , so Simpson is far cheaper for smooth .
The sample rule neither sorts nor takes absolute widths. Sorting would make a decreasing curve’s area positive and silently reconnect unsorted points into a different curve; np.abs(np.diff(x)) does the first. The caller’s order is meaningful (it is the threshold sweep), so the function measures exactly the polyline it was given.
The nodes come from linspace rather than a + i * h. With a rounded , need not equal , so the last node drifts. linspace pins both ends, and because scipy and the C port use the same nodes, results agree bit for bit.
Simpson raises on odd . scipy’s simpson accepts an odd number of intervals with a corrected last panel. That is a different rule with a different error constant; the contract keeps the classic composite rule and rejects what it does not implement.
One tradeoff is accepted. Fixed-step rules spend nodes uniformly, so for a function with a narrow peak, like Runge’s example, Simpson can be worse than the trapezoid until resolves the peak. Adaptive quadrature solves that at the cost of an unpredictable number of evaluations, which an ROC area or a reference test does not need.
What can go wrong
Section titled “What can go wrong”A correct solution reproduces the hand-worked values 5, 4.25, 4, and 4, and the ROC corners must give 0.625, since roc_auc is exactly this call. The rules must agree with scipy.integrate.trapezoid and simpson on the same nodes, for six functions and a reversed interval, and the sample rule must agree with scipy on uneven, unsorted, and decreasing samples, which is what ROC and reliability curves look like. The error orders are tested as properties: log-log slope 2 for the trapezoid and 4 for Simpson. Simpson must be exact on 40 random cubics with ; the trapezoid must be exact on lines but not on ; and must hold to rounding. Reversed and empty intervals must give and , and decreasing samples a negative area. The rules make one vectorized call to f on linspace(a, b, n + 1), which keeps results bit-identical across languages, and return a Python float rather than a numpy scalar, because callers compare and serialize it. Zero or one sample gives 0.0, which covers a one-threshold ROC curve. Odd or non-positive n, non-finite limits, a bad f, and bad samples all raise.
The usual mistakes look like this:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| a Riemann sum (left heights only) for samples | the hand ROC area is 0.375, not 0.625; AUCs biased low | ya[:-1] + ya[1:], halved: the mean of both heights |
| Simpson weights 2 and 4 swapped | order 2 instead of 4; the hand example gives 10/3 | 4.0 * odd on indices 1:-1:2, 2.0 * even on 2:-1:2 |
| accepting an odd number of Simpson steps | a plausible but wrong number | raises unless n >= 2 and n % 2 == 0 |
| counting the end points fully in the trapezoid rule | the hand example gives 9, order 1 | fx[0] / 2.0 and fx[-1] / 2.0 |
| sorting samples or using | a decreasing curve has positive area; unsorted samples are reconnected | plain np.diff(xa), no sort |
| nodes instead of | the last step is lost; the rules disagree with scipy | np.linspace(a, b, n + 1) |
| Simpson with the panel width in place of the step | every result doubled | h / 3.0 with h = (b - a) / n |
| assuming equal gaps between samples | wrong area on any real ROC curve | each step uses its own width from np.diff |
Warning: The left-Riemann-sum mistake is the one that ships. It produces a number between 0 and 1 that looks like an AUC, and it is biased low on every rising curve.
Where this leads
Section titled “Where this leads”The main consumer is roc_auc(scores, labels) in Logistic regression, ROC-AUC, and calibration, which builds the ROC corners and returns trapezoid(tpr, fpr). In AI Engineering, Bias and safety evals integrates the safety report’s ROC area and reliability curve the same way. Question 8 of the probability problem set on hypothesis tests and regression computes an AUC by hand, the same area seen as the fraction of pairs ranked correctly.
Further reading
Section titled “Further reading”- OpenStax, Calculus Volume 1 (free), sections 5.1 to 5.3 (the definite integral and the fundamental theorem), and Calculus Volume 2, section 3.6 (numerical integration).
- Sauer, Numerical Analysis, sections 5.2 and 5.3: Newton-Cotes rules and Romberg integration.
numpy.trapezoidandscipy.integrate.trapezoid(numpy/lib/_function_base_impl.py): integration along any axis of an N-d array.scipy.integrate.simpson(scipy/integrate/_quadrature.py): uneven sample spacing and an odd number of intervals with a corrected last panel.- Romberg integration and
scipy.integrate.quad(QUADPACKqags): adaptive Gauss-Kronrod quadrature that adds nodes only where the error estimate is large. sklearn.metrics.roc_auc_score(sklearn/metrics/_ranking.py,auc): the same corners and trapezoids, plus multiclass averaging.
Key terms
Section titled “Key terms”- Riemann sum: , the sum of thin rectangles under .
- definite integral: the limit of Riemann sums, the signed area between and the axis.
- fundamental theorem of calculus: if , then .
- quadrature: numerical computation of a definite integral.
- trapezoid rule: joining neighboring points by straight lines; second order, exact on lines.
- Simpson’s rule: fitting a parabola through each three points; fourth order, exact on cubics, needs an even number of steps.
- Romberg integration: repeated Richardson extrapolation of the trapezoid rule.
Summary
Section titled “Summary”- The definite integral is the signed area under , the limit of sums of thin slices; a computer stops at slices of width .
- The trapezoid rule joins neighboring points by straight lines: error proportional to , exact on lines.
- Simpson’s rule fits a parabola through each three points: error proportional to and, by a symmetry bonus, exact on cubics.
- Simpson is Richardson extrapolation of the trapezoid rule, , the same error-cancelling step used for finite differences.
- Samples that are not on a grid, such as the corners of an ROC curve, are integrated step by step with each step’s own signed width, in the order given.
Review questions
Section titled “Review questions”-
Why does
trapezoidusenp.diff(xa)without an absolute value or a sort?Answer
The widths are signed so that the order of the points is the direction of integration: decreasing gives a negative area, matching . Sorting or taking would change the curve being measured (or its orientation); an ROC curve’s corners come in threshold order, and that order is the curve.
-
Why does the hand ROC area come out as 0.625 and not 0.375?
Answer
Each step’s height is the mean of its two end heights, : the straight segment between corners, which is what an ROC curve is. 0.375 uses only the left height of each step, a left Riemann sum, which assumes the curve stays flat until the next corner and underestimates every rising curve.
-
Why must Simpson’s be even, and why does
simpsonraise rather than drop a step?Answer
Simpson fits one parabola per pair of steps, so the steps must pair up: the weight pattern only ends on 1 when is even. Dropping or patching a step would integrate a different interval or use a different rule with a different error, returning a plausible but wrong number. Raising makes the caller choose.
-
Simpson fits parabolas, so why is it exact on cubics?
Answer
On a panel around its midpoint, write the cubic as a quadratic plus . The quadratic part is integrated exactly by the parabola. is odd: its integral over is 0, and Simpson’s weights at also give . The error formula reflects this: it involves , which is 0 for a cubic.
-
What does being signed buy, and what happens for ?
Answer
With ,
linspaceruns downward and , so both rules return the negative of the forward integral with no extra branch. With , every node is and , so the result is exactly 0. Both are the signed-area rules of the definite integral, obtained by the same expression.