5.4.24 · D3Scientific Computing (Python)

Worked examples — Implementing numerical integration from scratch — trapezoidal, Simpson's

3,668 words17 min readBack to topic

Before anything, we recall the two machines we are feeding inputs into. Both take a function , an interval , and a number of equal slices . The slice width is the node spacing , and the points where we sample the curve are the nodes .


The error terms — where the signs come from

Before the examples we settle the two error formulas once, so every "Verify:" below can lean on them without hand-waving. We define the error as rule minus truth, . A positive means the rule overshoots.

Where actually comes from (a Taylor sketch)

We do not want you to trust the local error ; here is the argument in plain steps. Put one slice on (width , centred at for symmetry), and let be the midpoint value.

Step A — expand the curve. A Taylor series says that near the midpoint, Why? Taylor is the one tool that writes an unknown curve as "value + tilt + bend + …", exactly the pieces a straight chord can and cannot match.

Step B — integrate the true area. Over the symmetric slice the odd term integrates to , leaving Why? , and .

Step C — integrate the chord (what trapezoid actually computes). The trapezoid uses the two endpoint heights , whose average is Multiplying by the width gives the trapezoid area Why? The chord matches value and tilt but over-accounts the bend, because it samples the curve only at the two far ends where a convex curve is highest.

Step D — subtract. Local error = chord − truth: Why the plus? , so the chord's bend-term wins → positive local error, matching the convex-overshoot picture.

Now sum the slices: each contributes , and of them turns one factor of into :


The scenario matrix

Every cell below is a class of situation the topic can throw at you. The examples that follow are each tagged with the cell they cover.

# Case class What is special about it Example
C1 Exact case — polynomial within the rule's degree Error should be exactly zero (up to rounding) Ex 1
C2 Convex curve, overshoot sign Trapezoid over-estimates; which sign is the error? Ex 2
C3 Concave curve, undershoot sign Trapezoid under-estimates — the opposite sign Ex 3
C4 Rule fails silently — degree above what it captures Simpson is not exact; a residual error remains Ex 4
C5 Degenerate / reversed input, , , or Zero-width, flat, single slice, reversed limits Ex 5
C6 Odd trap for Simpson Parity bug: what to do when is odd Ex 6
C7 Convergence / limiting behaviour — halving Error must drop by (trap) and (Simpson) Ex 7
C8 Real-world word problem — data only, no formula You have measurements, not Ex 8
C9 Exam twist — sign change / negative area under axis Integral can be negative; "area" intuition misleads Ex 9

Example 1 — the exact case (C1)

Recall Why did

suffice? More slices would still give exactly 8 — refining a line changes nothing ::: because a straight line joining any two of its own points lies on the line, so every trapezoid is exact regardless of how many you use.


Example 2 — convex curve, trapezoid overshoots (C2)

Look at figure s01. The horizontal axis is on , the vertical axis is . The lavender curve is ; the green line is the two chords the trapezoids use. Takeaway: on a convex curve the chord lies above the curve, and the coral shaded slivers are the extra area the trapezoid wrongly counts — this is the overshoot made visible.

Figure — Implementing numerical integration from scratch — trapezoidal, Simpson's

Step 1. ; nodes ; . Why this step? Standard node table before plugging in.

Step 2. . Why this step? Endpoints weight 1, the single interior node weights 2.

Step 3. Compare: overshoot by . Why this step? The sign of the error is the whole point of this case.

Verify: For any convex () the chord lies above the curve, so . Using our fixed convention with , the plus coefficient makes — rule above truth. That matches the overshoot exactly in sign.


Example 3 — concave curve, trapezoid undershoots (C3)

Look at figure s02. Axes are the same ( horizontal on , vertical). The lavender curve is ; the green line is the trapezoid chords. Takeaway: the chord now sags below the arch, and the coral slivers are the area the trapezoid misses — the exact mirror image of s01, which is why the sign of the error flips.

Figure — Implementing numerical integration from scratch — trapezoidal, Simpson's

Step 1. ; nodes ; . Why this step? Sample the arch at its base, peak, base.

Step 2. . Why this step? Only the peak node contributes; endpoints are zero.

Step 3. undershoot by . Why this step? Concavity flips the sign compared to C2.

Verify: on , so with the plus coefficient times a negative gives — rule below truth. Undershoot confirmed. Together C2 and C3 prove the sign of the trapezoid error equals the sign of : convex overshoots, concave undershoots.


Example 4 — Simpson is not exact (C4)

Look at figure s05. The lavender curve is ; the mint dashed curve is the parabola Simpson fits through the three nodes . Takeaway: the parabola cannot follow the sharp late upturn of , and the coral gap between them is the degree-4 error Simpson cannot absorb — this is why the answer is not exact.

Figure — Implementing numerical integration from scratch — trapezoidal, Simpson's

Step 1. ; nodes ; . Why this step? at is — do not confuse with .

Step 2. Why this step? The 1-4-1 stencil, peak node weight 4.

Step 3. True value is , so the estimate overshoots: . Why this step? This is the case where the rule almost wins but leaks a fourth-degree error.

Verify — which error form, and why. Our whole interval is a single Simpson pair (only slices), so the natural tool is the per-pair error, not the composite one — using the composite here would double-count the pair structure. With the per-pair form, width and : This gives under the truth-minus-rule grouping used to derive the classic sign. Our page convention is , which flips it to — matching the computed overshoot. The magnitude is unambiguous; only the printed sign depends on the convention — exactly the sign trap flagged earlier. Either way, "Simpson is exact" holds only up to degree 3.


Example 5 — degenerate and reversed inputs (C5)

Step 1 — zero-width interval. . Every term is multiplied by , so . Why this step? An interval of no width encloses no area — the formula must return , and it does because zeroes the whole sum. No crash.

Step 2 — flat function. on . Every , so the weighted sum is ; . True integral . Exact. Why this step? Zero is a degree-0 polynomial — inside both rules' exactness, so no error possible.

Step 3 — single slice () and why Simpson can't. Trapezoid with has no interior nodes; the sum is empty and — a valid single trapezoid. Simpson with is mathematically impossible: Simpson's rule is the exact integral of the parabola through three nodes, but gives only two nodes (). Two points determine a line, never a unique parabola, so there is no parabola to integrate — the rule is undefined, and the code's ValueError is the honest report of that. Why this step? Knowing it fails for a geometric reason (too few points), not a coding whim, stops off-by-one panics.

Step 4 — reversed limits. : here , so . Redo Example 2's trapezoid arithmetic with the negative : nodes , , . Why this step? The negative carries the sign for you, so the estimate is exactly the forward answer.

Verify: (a) , (b) , (c) on of gave in Example 1, (d) , matching . All consistent. The only genuine crash is (then blows up), which is why production code must guard n >= 1.


Example 6 — the odd- Simpson trap (C6)

Step 1. is odd. The 1-4-1 stencil eats slices two at a time; with 3 slices one is left with no partner parabola. Why this step? This is the structural reason parity matters, not a coding whim.

Step 2. The parent's code checks if n % 2 == 1: raise ValueError. So the call refuses loudly — the best outcome, better than a silent lie. Why this step? A raised error is a feature: it stops the #1 silent bug in its tracks.

Step 3 — the fix. Two clean options: (i) bump to the next even (here ), or (ii) apply Simpson to the first even number of slices and handle the final dangling slice with a trapezoid. Simplest for an exam: choose even from the start. Why this step? You must be able to repair the case, not just detect it.

Verify: Redo with the fixed : , nodes , . — exact, as expected for a parabola. The even works flawlessly.


Example 7 — convergence / limiting behaviour (C7)

Look at figure s03. The horizontal axis is the number of subintervals (values ); the vertical axis is the trapezoid error on a logarithmic scale (so equal drops mean equal ratios). Takeaway: the three lavender dots fall in a straight line on the log axis, and each coral "÷4" label marks that doubling divides the error by exactly — the visual fingerprint of the factor.

Figure — Implementing numerical integration from scratch — trapezoidal, Simpson's

Step 1. : from Example 2, , error . Why this step? Reuse the known value as the baseline.

Step 2. : , nodes , . . Error . Why this step? One doubling of to test the ratio.

Step 3. : computing the eight-node sum gives , error . Why this step? A second doubling confirms the pattern is not a fluke.

Step 4 — conclude. Error ratios: and . Exactly per doubling. Why this step? This closes the demonstration: the halving of has been carried all the way to a numeric verdict.

Verify: The drop is precisely the factor in : halving multiplies by . (This is exactly why Richardson extrapolation can combine and to cancel the term and manufacture Simpson.)


Example 8 — real-world word problem, data only (C8)

Step 1. Identify the integral. Distance is the area under the speed–time curve, , and our data spacing is uniform: s. Why this step? Numerical integration is the only tool when you have samples, not a symbolic .

Step 2. Count slices: 5 points ⇒ subintervals. is even, so Simpson is allowed — use it for higher accuracy. Why this step? Points ; check parity before choosing Simpson.

Step 3 — Simpson. m. Why this step? Odd-index nodes (10, 30) get weight 4; the even interior node (22) gets weight 2.

Step 4 — trapezoid cross-check. m. Why this step? A second method within a hair of the first is strong evidence we did not blunder.

Verify: Both give m; they agree to , sensible for a car accelerating for 8 s. Units: ✓ — an integral over time of speed yields distance, dimensionally correct.


Example 9 — exam twist: signed area (C9)

Look at figure s04. Horizontal axis on , vertical axis , with the -axis drawn in. The mint region is the positive hill on (area ); the coral region is the negative valley on (area ). Takeaway: numerical rules compute signed area — heights below the axis are negative and subtract — so the two regions cancel to .

Figure — Implementing numerical integration from scratch — trapezoidal, Simpson's

Step 1. True value: . Why this step? The truth exposes the trap: the answer is zero, not a large area.

Step 2. ; nodes ; . Why this step? Note the negative sample at — that is where intuition fails newcomers.

Step 3. . Why this step? The weight-4 peaks and cancel; the answer is exactly .

Verify: true value. If the exam wanted the geometric area (total shaded region regardless of sign), you would integrate or split at and add and to get . Always ask: signed integral or geometric area? — they differ whenever the curve crosses the axis.


Connections

  • Parent topic — the derivations these examples exercise.
  • Riemann sums — the limit the exact cases (C1) reduce to.
  • Newton-Cotes formulas — why trapezoid caps at degree 1 and Simpson at degree 3 (C4).
  • Polynomial interpolation — Simpson integrates the interpolating parabola of Ex 4's figure.
  • Taylor series — origin of the and error terms derived and verified here.
  • Richardson extrapolation — the error drop in Ex 7 is what makes it work.
  • scipy.integrate.quad — how production code handles the data/word-problem case (Ex 8) adaptively.

Concept Map

sign of f''

sign of f''

h squared

Scenario matrix

C1 exact case

C2 convex overshoot

C3 concave undershoot

C4 residual error

C5 degenerate or reversed

C6 odd n trap

C7 convergence

C8 data only

C9 signed area

Error sign = sign of f''

Error order O h^2