Mathematical Foundations

III.15 · Calculus

How quickly does a numerical integral converge — and when does it slow down?

Refine rectangle, midpoint and trapezoid rules by doubling the number of panels. Measure how fast each error shrinks, and see smoothness — not the rule alone — decide the rate.

Refine a quadrature rule and measure its order

Rule

trapezoid rule, n = 4, for f(x) = x² on [0, 1]

f(x) = x² (smooth; exact answer 1/3). 4 trapezoid panels are drawn. Approximation 0.34375, reference 1/3.

log₁₀|error| vs k (n = 2ᵏ): selected rule solid, other rules dashed

Errors of all four rules for n = 1 … 1024 on a log scale. The selected trapezoid rule has error 1.04×10⁻² at n = 4; halving h divided it by about 4.00.

Panels (n = 2ᵏ)
4
Rule
trapezoid
Approximation
0.34375
Reference integral
1/30.333333…
Error
1/960.010417…
Observed order (log₂ of the error ratio for n/2 and n)
2
Expected order for smooth f
2

Exact values use =; binary64 approximations use ≈. Undefined values state their reason.

Halving h divides the trapezoid error by about 4.00: observed order 2.00, expected 2 for smooth f.

h=b−an=1−04h=\frac{b-a}{n}=\frac{1-0}{4}
Qn=0.34375Q_n=0.34375
∫01f dx=13\int_{0}^{1}f\,dx=\frac{1}{3}
∣Qn−I∣=196|Q_n-I|=\frac{1}{96}
∣Tn−I∣≤(b−a) h212max⁡∣f′′∣  (f′′ bounded)|T_n-I|\le\frac{(b-a)\,h^2}{12}\max|f''|\ \ (f''\text{ bounded})
∣Ln−I∣≤(b−a) h2max⁡∣f′∣|L_n-I|\le\frac{(b-a)\,h}{2}\max|f'|
trapezoid rule: error and observed order as n doubles
knQₙ − I (signed)observed order
011/6—
121/242.000
241/962.000
381/3842.000
4161/15362.000
5321/61442.000
6641/245762.000
71281/983042.000
82561/3932162.000
95121/15728642.000
1010241/62914562.000

n = 1

Error 1/6.

n=1: ∣Qn−I∣=16n=1:\ |Q_n-I|=\frac{1}{6}

from 0 to 10, whole numbers only

Choose a rule and refinement level k (n = 2ᵏ panels). The left plane draws the panels; the right plane plots log₁₀ of the error for all four rules as n doubles — the slope is the convergence order.

For ∫01x2 dx=1/3\int_0^1x^2\,dx=1/3, four trapezoids give 11/3211/32, an error of exactly 1/961/96. Each doubling of nn divides the trapezoid error by exactly 44 and the left-rule error by about 22. Now choose √x: slower: the trapezoid error shrinks by only about 21.52^{1.5} per doubling, because x\sqrt x has an infinite slope at 00.

Intuition: how much does each refinement buy?

Every rule replaces ff on each panel by something simpler — a constant for rectangle rules, a straight line for the trapezoid rule. Halving the panel width hh makes the replacement better. How much better depends on how closely the simple shape follows the curve, which depends on the rule and on how smooth ff is. Plotting log⁡(error)\log(\text{error}) against the refinement level turns a rate hph^p into a straight line with slope pp.

Definition

With nn panels of width h=(b−a)/nh=(b-a)/n and points xi=a+ihx_i=a+ih:

Ln=h∑i=0n−1f(xi),L_n=h\sum_{i=0}^{n-1}f(x_i), Mn=h∑i=0n−1f(xi+xi+12),M_n=h\sum_{i=0}^{n-1}f\Big(\frac{x_i+x_{i+1}}2\Big), Tn=h(12f(x0)+f(x1)+⋯+f(xn−1)+12f(xn)),\begin{aligned}T_n=h\Big(&\tfrac12f(x_0)+f(x_1)+\cdots\\&+f(x_{n-1})+\tfrac12f(x_n)\Big),\end{aligned}

and RnR_n uses right endpoints. A rule has order pp for a class of functions if its error behaves like ChpCh^p. The observed order from two refinements is p≈log⁡2(En/E2n)p\approx\log_2(E_{n}/E_{2n}).

Mechanics: what the explorer computes

For x2x^2, x3−xx^3-x and ∣x−1/3∣|x-1/3| every approximation and every error is an exact rational, computed for n=1,2,4,…,1024n=1,2,4,\dots,1024. For sin⁡x\sin x and x\sqrt x the values are binary64, with references 1−cos⁡31-\cos3 and 2/32/3 from their antiderivatives. Panels are drawn while they are wider than a pixel. The convergence plot and table come from the same computed errors.

Derivation: why the trapezoid rule has order 2

On one panel [xi,xi+h][x_i,x_i+h], the trapezoid replaces ff by its linear interpolant. The interpolation error is 12f′′(ξ)(t−xi)(t−xi−h)\tfrac12f''(\xi)(t-x_i)(t-x_i-h), and integrating over the panel gives −h312f′′(ξi)-\tfrac{h^3}{12}f''(\xi_i). Summing n=(b−a)/hn=(b-a)/h panels,

Tn−∫abf=−(b−a) h212f′′(ξ)T_n-\int_a^b f=-\frac{(b-a)\,h^2}{12}f''(\xi)

for some ξ\xi, provided f′′f'' is continuous. So halving hh quarters the error. A rectangle rule replaces ff by a constant and loses a factor hh: order 11. The midpoint rule is order 22 with half the trapezoid’s constant and the opposite sign.

Worked example

∫01x2 dx=1/3\int_0^1x^2\,dx=1/3. With nn trapezoids the error is exactly 1/(6n2)1/(6n^2): n=1n=1 gives 1/21/2 (error 1/61/6), n=2n=2 gives 3/83/8 (error 1/241/24), n=4n=4 gives 11/3211/32 (error 1/961/96). The midpoint error is exactly −1/(12n2)-1/(12n^2), and the left-rule error is −1/(2n)+1/(6n2)-1/(2n)+1/(6n^2), which approaches order 11.

Replay the worked derivation

n = 1

Error 1/6.

n=1: ∣Qn−I∣=16n=1:\ |Q_n-I|=\frac{1}{6}
Replay the trapezoid errors for n = 1, 4, 16, 64, 256, 1024.

When the rate changes

  • Singular slope. x\sqrt x has f′→∞f'\to\infty at 00; the h2h^2 bound does not apply and the trapezoid error behaves like h1.5h^{1.5}.
  • A corner off the grid. ∣x−1/3∣|x-1/3| has a corner that never falls on a grid point k/2mk/2^m; the first refinements behave irregularly before settling.
  • Signed integrands. For x3−xx^3-x on [−1,2][-1,2], positive and negative parts partly cancel in the exact value 9/49/4; the rules must resolve both.
  • No universal promise. Highly oscillatory or discontinuous integrands can make any fixed rule converge slowly or appear to converge to the wrong value for small nn.

Executable reference code

The reference computes exact errors of all four rules with Fraction and recovers the observed orders 11 and 22 for x2x^2. The NumPy version measures observed orders for sin⁡x\sin x and x\sqrt x and shows the drop from 22 to about 1.51.5.

code/python/calculus_quadrature.py
"""Exact errors of four quadrature rules for x**2 on [0, 1]; observed orders 1 and 2 (III.15)."""
from fractions import Fraction as F
import math


def rule(name, f, a, b, n):
    h = (b - a) / n
    x = [a + i * h for i in range(n + 1)]
    if name == "left":
        return h * sum(f(t) for t in x[:-1])
    if name == "right":
        return h * sum(f(t) for t in x[1:])
    if name == "midpoint":
        return h * sum(f((s + t) / 2) for s, t in zip(x, x[1:]))
    return h * (f(x[0]) / 2 + sum(f(t) for t in x[1:-1]) + f(x[-1]) / 2)


f = lambda t: t * t
exact = F(1, 3)
for n in (1, 2, 4, 8, 16):
    assert rule("trapezoid", f, F(0), F(1), n) - exact == F(1, 6 * n * n)
    assert rule("midpoint", f, F(0), F(1), n) - exact == F(-1, 12 * n * n)
    assert rule("left", f, F(0), F(1), n) - exact == F(-1, 2 * n) + F(1, 6 * n * n)

order = lambda e1, e2: math.log2(abs(e1) / abs(e2))
e = [rule("left", f, F(0), F(1), 2**k) - exact for k in range(8, 10)]
assert abs(order(*e) - 1) < 0.01
code/python/calculus_quadrature_numpy.py
"""Observed trapezoid orders: about 2 for sin on [0, 3], about 1.5 for sqrt on [0, 1] (III.15)."""
import numpy as np

def trapezoid(f, a, b, n):
    x = np.linspace(a, b, n + 1)
    return np.trapezoid(f(x), x)

def observed(f, a, b, exact, k):
    e1, e2 = abs(trapezoid(f, a, b, 2**k) - exact), abs(trapezoid(f, a, b, 2**(k + 1)) - exact)
    return np.log2(e1 / e2)

assert abs(observed(np.sin, 0, 3, 1 - np.cos(3), 8) - 2) < 0.05
assert abs(observed(np.sqrt, 0, 1, 2 / 3, 10) - 1.5) < 0.05

Explore

Compare the trapezoid and midpoint curves: parallel lines, the midpoint one lower by a factor 22. On the signed integrand, switch to the left rule and watch the order drop to 11. On sin x, push kk to 1010: the error approaches 10−610^{-6}, still far above rounding level.

Common mistakes

Assuming more panels always gives the promised rate regardless of smoothness. Reading the error from a single nn instead of its behaviour under refinement. Confusing the number of panels with the number of function evaluations (the trapezoid rule uses n+1n+1 points).

Numerical considerations

For smooth integrands, higher-order rules (Simpson’s rule, Gaussian quadrature) reach small errors with far fewer evaluations; adaptive methods refine only where the integrand needs it. At very large nn rounding in the sum eventually matters. Reliable software reports an error estimate, usually from comparing two refinements, exactly as the observed-order column does.

Engineering and ML connections

Numerical integration computes expectations, normalising constants, areas under curves and solutions of differential equations (one step of many ODE methods is a quadrature rule). Monte Carlo integration (Part IV) trades the deterministic rates here for a rate of n−1/2n^{-1/2} that does not depend on dimension.

Exercises

calculation

One trapezoid

Approximate ∫ from 0 to 1 of x² dx with one trapezoid. Give the value and the error.

calculation

One midpoint panel

Approximate ∫ from 0 to 1 of x² dx with one midpoint panel. Give the value.

calculation

Read an observed order

The error drops from 0.04 to 0.01 when n doubles. What is the observed order p in error ∝ hᵖ?

prediction

A slower case

The trapezoid rule on ∫₀¹ √x dx converges with order about 1.5, not 2. Why?

Choose one answer

prediction

A universal guarantee?

Does doubling n always quarter the trapezoid error?

Choose one answer

Summary and checkpoints

Rectangle rules converge with order 1, trapezoid and midpoint rules with order 2 — for smooth integrands. Singularities and corners lower the observed order; signed integrands require resolving cancellation. Measure convergence by refinement rather than trusting a single approximation. This completes Part III: the next Part turns to probability, where integrals of densities measure chance.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available