Skip to content

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.

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.

Cut [a,b][a, b] into nn slices of width hh, stand a rectangle on each slice with the height of ff somewhere in it, and add the areas: ∑if(ξi) h\sum_i f(\xi_i)\, h. This is a Riemann sum. As h→0h \to 0 the sums for a continuous ff settle on one number whatever points ξi\xi_i you chose, and that number is the definite integral ∫abf(x) dx\int_a^b f(x)\,dx. Area below the axis counts as negative, which is why it is a signed area. Running from bb to aa makes every width −h-h, so ∫baf=−∫abf\int_b^a f = -\int_a^b f, and an interval of length 0 has integral 0. A computer stops at nn slices.

The fundamental theorem of calculus links this area to derivatives: if FF is an antiderivative of ff, meaning F′=fF' = f, then ∫abf(x) dx=F(b)−F(a)\int_a^b f(x)\,dx = F(b) - F(a). For f(x)=x3f(x) = x^3, F(x)=x4/4F(x) = x^4/4, so ∫02x3 dx=16/4−0=4\int_0^2 x^3\,dx = 16/4 - 0 = 4. Most integrals met in practice have no FF in closed form (e−x2/2e^{-x^2/2}, the shape of the normal density, is the famous one), or ff is known only at sample points. Then the area is computed numerically, which is called quadrature.

In what follows, nn is the number of equal steps, h=(b−a)/nh = (b - a)/n is the step, xi=a+ihx_i = a + ih for i=0,…,ni = 0, \ldots, n are the nodes (numpy.linspace(a, b, n + 1)), and fi=f(xi)f_i = f(x_i). Replace ff on one step [xi,xi+1][x_i, x_{i+1}] by the straight line through its two end values. The region under that line is a trapezoid with parallel sides fif_i and fi+1f_{i+1} and width hh, so its area is h (fi+fi+1)/2h\,(f_i + f_{i+1})/2: the width times the average height. A straight line is integrated exactly, because the “approximation” is the function itself.

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 hh is

T(h)=h(12f0+f1+f2+⋯+fn−1+12fn).T(h) = h\left(\tfrac{1}{2} f_0 + f_1 + f_2 + \cdots + f_{n-1} + \tfrac{1}{2} f_n\right).

Simpson’s rule instead takes the steps in pairs and fits the parabola through the three points at x2j,x2j+1,x2j+2x_{2j}, x_{2j+1}, x_{2j+2}. The area under that parabola, over a panel of width 2h2h, is h3(f2j+4f2j+1+f2j+2)\frac{h}{3}(f_{2j} + 4 f_{2j+1} + f_{2j+2}); to check it, integrate the parabola through (−h,f−),(0,f0),(h,f+)(-h, f_-), (0, f_0), (h, f_+) term by term. Adding the panels, every even inner node is shared by two panels:

S(h)=h3(f0+4f1+2f2+4f3+2f4+⋯+2fn−2+4fn−1+fn).S(h) = \frac{h}{3}\left(f_0 + 4 f_1 + 2 f_2 + 4 f_3 + 2 f_4 + \cdots + 2 f_{n-2} + 4 f_{n-1} + f_n\right).

The pattern 1, 4, 2, 4, …, 2, 4, 1 closes only when nn is even. An odd nn is not a smaller Simpson’s rule; it is a different, wrong one, so the contract raises instead of rounding.

An ROC curve is a list of points (xi,yi)(x_i, y_i) with uneven gaps, produced by sweeping a threshold. Its area is the trapezoid rule applied step by step with each step’s own width: ∑i(xi+1−xi)(yi+yi+1)/2\sum_i (x_{i+1} - x_i)(y_i + y_{i+1})/2. 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 bb to aa. 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.

Expand ff 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 −h312f′′(ξ)-\frac{h^3}{12} f''(\xi) for some ξ\xi in the step. There are n=(b−a)/hn = (b - a)/h steps, so the composite errors are

∫abf−T(h)=−(b−a) h212 f′′(ξ),∫abf−S(h)=−(b−a) h4180 f(4)(ξ).\int_a^b f - T(h) = -\frac{(b - a)\, h^2}{12}\, f''(\xi), \qquad \int_a^b f - S(h) = -\frac{(b - a)\, h^4}{180}\, f^{(4)}(\xi).

The trapezoid rule is second order: halve hh and the error drops by 4. Simpson is fourth order: halve hh and it drops by 16. A parabola should only be exact on quadratics, yet the error involves f(4)f^{(4)}, so Simpson is exact on cubics too: the x3x^3 error on the left half of a panel cancels the one on the right half by symmetry. The table shows both rules on ∫0πsin⁡x dx=2\int_0^\pi \sin x\,dx = 2:

nn2481632
trapezoid error4.3×10−14.3 \times 10^{-1}1.0×10−11.0 \times 10^{-1}2.6×10−22.6 \times 10^{-2}6.4×10−36.4 \times 10^{-3}1.6×10−31.6 \times 10^{-3}
Simpson error9.4×10−29.4 \times 10^{-2}4.6×10−34.6 \times 10^{-3}2.7×10−42.7 \times 10^{-4}1.7×10−51.7 \times 10^{-5}1.0×10−61.0 \times 10^{-6}

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 ff is smooth at the scale of hh. On Runge’s peak 1/(1+25x2)1/(1 + 25x^2) over [−1,1][-1, 1] with n=8n = 8, 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 hh resolves the function.

The trapezoid error is not just O(h2)O(h^2); it is a series in even powers, T(h)=I+c2h2+c4h4+⋯T(h) = I + c_2 h^2 + c_4 h^4 + \cdots, where II 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:

4 T(h)−T(2h)3=I+O(h4).\frac{4\,T(h) - T(2h)}{3} = I + O(h^4).

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 16,64,…16, 64, \ldots) is Romberg integration. The solution’s simpson and trapezoid_rule satisfy this identity to rounding.

Take ∫02x3 dx=4\int_0^2 x^3\,dx = 4 and apply each rule:

RuleNodes and valuesComputationValueError
TT, n=2n = 2, h=1h = 1f(0,1,2)=0,1,8f(0, 1, 2) = 0, 1, 81⋅(0/2+1+8/2)1 \cdot (0/2 + 1 + 8/2)51
TT, n=4n = 4, h=0.5h = 0.5f(0,0.5,1,1.5,2)=0,0.125,1,3.375,8f(0, 0.5, 1, 1.5, 2) = 0, 0.125, 1, 3.375, 80.5⋅(0+0.125+1+3.375+4)0.5 \cdot (0 + 0.125 + 1 + 3.375 + 4)4.250.25
SS, n=2n = 2, h=1h = 10,1,80, 1, 813(0+4⋅1+8)\frac{1}{3}(0 + 4 \cdot 1 + 8)40
RichardsonT(0.5)T(0.5), T(1)T(1)(4⋅4.25−5)/3=12/3(4 \cdot 4.25 - 5)/3 = 12/340

Halving hh divided the trapezoid error by exactly 4 (here f′′=6xf'' = 6x and the error formula is exact up to the mean value). Simpson is exact because x3x^3 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: (0,0)(0, 0), (0.5,0.75)(0.5, 0.75), (1,1)(1, 1). The two trapezoids have areas 0.5⋅(0+0.75)/2=0.18750.5 \cdot (0 + 0.75)/2 = 0.1875 and 0.5⋅(0.75+1)/2=0.43750.5 \cdot (0.75 + 1)/2 = 0.4375, for a total of 0.625. Counting each step at its left height only (a left Riemann sum) gives 0.5⋅0+0.5⋅0.75=0.3750.5 \cdot 0 + 0.5 \cdot 0.75 = 0.375.

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 ff 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; b<ab < a 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.

Seven decisions produce the solution.

  1. For samples, use one trapezoid per step with its signed width. Step ii contributes (xi+1−xi)(yi+yi+1)/2(x_{i+1} - x_i)(y_i + y_{i+1})/2. 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.
  2. 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.
  3. For functions, evaluate once on fixed nodes. The nodes are np.linspace(a, b, n + 1): nn steps need n+1n + 1 nodes, and linspace puts the first and last exactly at aa and bb. One vectorized call to f returns all fif_i, which keeps every implementation of the contract (Python, C, scipy) on the same nodes and so on the same rounding.
  4. Let the step carry the direction. h=(b−a)/nh = (b - a)/n is negative when b<ab < a and zero when a=ba = b, so the composite formulas give −∫ab-\int_a^b and 00 with no special cases.
  5. Apply the trapezoid weights. The end nodes get 12\tfrac12, inner nodes 1, all times hh.
  6. Apply the Simpson weights. h3\tfrac{h}{3} times 1,4,2,4,…,2,4,11, 4, 2, 4, \ldots, 2, 4, 1. Odd-indexed nodes are the parabola midpoints (weight 4), even inner nodes are shared by two panels (weight 2). This closes only for even nn, so odd nn raises.
  7. Validate everything that could make the area meaningless. Non-finite limits or samples, mismatched lengths, an f that returns the wrong shape or a non-finite value, and bad n all raise ValueError rather 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 [0.5,0.5][0.5, 0.5] and ya[:-1] + ya[1:] is [0.75,1.75][0.75, 1.75]; the products sum to 1.251.25, and halving gives 0.6250.625. 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 ∫02x3\int_0^2 x^3 with n=2n = 2, the nodes are 0,1,20, 1, 2, fx is [0,1,8][0, 1, 8], odd is 1, even is the empty sum 0, and the result is 13(0+4+0+8)=4\tfrac13(0 + 4 + 0 + 8) = 4. With trapezoid_rule and n=2n = 2: 1⋅(0+1+4)=51 \cdot (0 + 1 + 4) = 5. The Richardson identity holds node by node: 4T(h)−T(2h)4T(h) - T(2h) gives hh times 1,4,2,4,…,11, 4, 2, 4, \ldots, 1, and dividing by 3 is exactly the simpson expression. The full solution is in integrate.py.

All three functions are O(n)O(n) in time and memory: one pass of np.diff and a sum for samples, and one call to f on n+1n + 1 nodes for the rules. To reach an error δ\delta the trapezoid rule needs n∝δ−1/2n \propto \delta^{-1/2} nodes and Simpson n∝δ−1/4n \propto \delta^{-1/4}, so Simpson is far cheaper for smooth ff.

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 hh, a+nha + nh need not equal bb, 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 nn. 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 hh 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.

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 n=2,4,10n = 2, 4, 10; the trapezoid must be exact on lines but not on x2x^2; and S=(4T(h)−T(2h))/3S = (4T(h) - T(2h))/3 must hold to rounding. Reversed and empty intervals must give ∫ba=−∫ab\int_b^a = -\int_a^b and ∫aa=0\int_a^a = 0, 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:

PitfallSymptomHow the solution avoids it
a Riemann sum (left heights only) for samplesthe hand ROC area is 0.375, not 0.625; AUCs biased lowya[:-1] + ya[1:], halved: the mean of both heights
Simpson weights 2 and 4 swappedorder 2 instead of 4; the hand example gives 10/34.0 * odd on indices 1:-1:2, 2.0 * even on 2:-1:2
accepting an odd number of Simpson stepsa plausible but wrong numberraises unless n >= 2 and n % 2 == 0
counting the end points fully in the trapezoid rulethe hand example gives 9, order 1fx[0] / 2.0 and fx[-1] / 2.0
sorting samples or using ∣Δx∣\lvert \Delta x \rverta decreasing curve has positive area; unsorted samples are reconnectedplain np.diff(xa), no sort
nn nodes instead of n+1n + 1the last step is lost; the rules disagree with scipynp.linspace(a, b, n + 1)
Simpson with the panel width 2h2h in place of the step hhevery result doubledh / 3.0 with h = (b - a) / n
assuming equal gaps between sampleswrong area on any real ROC curveeach 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.

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.

  • 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.trapezoid and scipy.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 (QUADPACK qags): 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.
  • Riemann sum: ∑if(ξi) h\sum_i f(\xi_i)\, h, the sum of thin rectangles under ff.
  • definite integral: the limit of Riemann sums, the signed area between ff and the xx axis.
  • fundamental theorem of calculus: if F′=fF' = f, then ∫abf=F(b)−F(a)\int_a^b f = F(b) - F(a).
  • 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.
  • The definite integral ∫abf(x) dx\int_a^b f(x)\,dx is the signed area under ff, the limit of sums of thin slices; a computer stops at nn slices of width hh.
  • The trapezoid rule joins neighboring points by straight lines: error proportional to h2h^2, exact on lines.
  • Simpson’s rule fits a parabola through each three points: error proportional to h4h^4 and, by a symmetry bonus, exact on cubics.
  • Simpson is Richardson extrapolation of the trapezoid rule, (4T(h/2)−T(h))/3(4T(h/2) - T(h))/3, 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.
  1. Why does trapezoid use np.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 xx gives a negative area, matching ∫baf=−∫abf\int_b^a f = -\int_a^b f. Sorting or taking ∣Δx∣|\Delta x| would change the curve being measured (or its orientation); an ROC curve’s corners come in threshold order, and that order is the curve.

  2. 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, (yi+yi+1)/2(y_i + y_{i+1})/2: 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.

  3. Why must Simpson’s nn be even, and why does simpson raise rather than drop a step?

    Answer

    Simpson fits one parabola per pair of steps, so the steps must pair up: the weight pattern 1,4,2,…,4,11, 4, 2, \ldots, 4, 1 only ends on 1 when nn 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.

  4. Simpson fits parabolas, so why is it exact on cubics?

    Answer

    On a panel [−h,h][-h, h] around its midpoint, write the cubic as a quadratic plus c x3c\,x^3. The quadratic part is integrated exactly by the parabola. x3x^3 is odd: its integral over [−h,h][-h, h] is 0, and Simpson’s weights h3(1,4,1)\tfrac h3(1, 4, 1) at −h,0,h-h, 0, h also give h3(−h3+0+h3)=0\tfrac h3(-h^3 + 0 + h^3) = 0. The error formula reflects this: it involves f(4)f^{(4)}, which is 0 for a cubic.

  5. What does h=(b−a)/nh = (b - a)/n being signed buy, and what happens for a=ba = b?

    Answer

    With b<ab < a, linspace runs downward and h<0h < 0, so both rules return the negative of the forward integral with no extra branch. With a=ba = b, every node is aa and h=0h = 0, so the result is exactly 0. Both are the signed-area rules of the definite integral, obtained by the same expression.