Mathematical Foundations

III.14 · Calculus

Why is a smaller step not always a better derivative?

Compute forward, backward and centered difference quotients in binary64 for steps from 10⁻¹ to 10⁻¹⁶. The error first falls with h, then rises again — two error sources trade places.

Shrink h and watch two errors compete

log₁₀|error| vs log₁₀ h: forward (blue), backward (dashed green), centered (orange), budgets (dashed purple)

Observed errors of three binary64 difference quotients of f(x) = sin x at x = 1 for h = 10⁻¹ … 10⁻¹⁶, against the reference derivative cos x. Errors first fall (truncation) then rise (rounding); the dashed curves are the documented error budgets. At h = 10⁻⁴: forward 4.21×10⁻⁵, centered 9.00×10⁻¹⁰.

Point
1
Step
10⁻⁴
Reference derivative (cos x)
0.540302
Forward difference
0.540260
Backward difference
0.540344
Centered difference
0.540302
Forward error
4.21×10⁻⁵
Centered error
9.00×10⁻¹⁰
Forward truncation budget
5.00×10⁻⁵
Forward rounding budget
3.80×10⁻¹²
Machine epsilon (binary64)
2.22×10⁻¹⁶

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

At h = 10⁻⁴ truncation dominates: shrinking h still helps. The centered difference (error 9.00×10⁻¹⁰) beats forward (4.21×10⁻⁵) because its truncation error is O(h²).

D+=f(x+h)−f(x)h,D−=f(x)−f(x−h)hD_+=\frac{f(x+h)-f(x)}{h},\quad D_-=\frac{f(x)-f(x-h)}{h}
D0=f(x+h)−f(x−h)2hD_0=\frac{f(x+h)-f(x-h)}{2h}
∣D+−f′∣≲h2max⁡∣f′′∣⏟truncation+ε (∣f(x+h)∣+∣f(x)∣)h⏟rounding,ε=2−52|D_+-f'|\lesssim \underbrace{\tfrac{h}{2}\max|f''|}_{\text{truncation}}+\underbrace{\frac{\varepsilon\,(|f(x+h)|+|f(x)|)}{h}}_{\text{rounding}},\quad \varepsilon=2^{-52}
∣D0−f′∣≲h26max⁡∣f′′′∣+ε (∣f(x+h)∣+∣f(x−h)∣)2h|D_0-f'|\lesssim \tfrac{h^2}{6}\max|f'''|+\frac{\varepsilon\,(|f(x+h)|+|f(x-h)|)}{2h}
h+∗≈4ε∣f∣/∣f′′∣≈2.73×10−8,h0∗≈3ε∣f∣/∣f′′′∣3≈8.25×10−6h^*_{+}\approx\sqrt{4\varepsilon|f|/|f''|}\approx 2.73\times10^{-8},\qquad h^*_{0}\approx\sqrt[3]{3\varepsilon|f|/|f'''|}\approx 8.25\times10^{-6}
Errors of binary64 quotients against the independent reference derivative cos x
khforward errorcentered errorforward budget
110⁻¹4.29×10⁻²9.00×10⁻⁴2.00×10⁻¹
210⁻²4.22×10⁻³9.00×10⁻⁶2.00×10⁻²
310⁻³4.21×10⁻⁴9.01×10⁻⁸2.00×10⁻³
410⁻⁴4.21×10⁻⁵9.00×10⁻¹⁰2.00×10⁻⁴
510⁻⁵4.21×10⁻⁶1.11×10⁻¹¹2.00×10⁻⁵
610⁻⁶4.21×10⁻⁷2.77×10⁻¹¹2.00×10⁻⁶
710⁻⁷4.18×10⁻⁸1.94×10⁻¹⁰2.16×10⁻⁷
810⁻⁸2.97×10⁻⁹2.58×10⁻⁹1.83×10⁻⁷
910⁻⁹5.25×10⁻⁸2.97×10⁻⁹1.68×10⁻⁶
1010⁻¹⁰5.85×10⁻⁸5.85×10⁻⁸1.51×10⁻⁵
1110⁻¹¹1.17×10⁻⁶1.17×10⁻⁶1.50×10⁻⁴
1210⁻¹²4.32×10⁻⁵1.23×10⁻⁵1.69×10⁻³
1310⁻¹³7.34×10⁻⁴1.79×10⁻⁴1.67×10⁻²
1410⁻¹⁴3.71×10⁻³3.71×10⁻³1.51×10⁻¹
1510⁻¹⁵1.48×10⁻²1.48×10⁻²1.73×10⁰
1610⁻¹⁶5.40×10⁻¹1.48×10⁻²1.71×10¹

h = 10⁻¹

Forward error 4.29×10⁻² (budget: truncation 5.00×10⁻², rounding 4.30×10⁻¹⁵); centered error 9.00×10⁻⁴.

h=10−1:∣D+−f′∣≈4.29×10−2,∣D0−f′∣≈9.00×10−4h=10^{-1}:\quad |D_+-f'|\approx 4.29\times10^{-2},\quad |D_0-f'|\approx 9.00\times10^{-4}

from −3 to 3, up to 2 decimal places

from 1 to 16, whole numbers only

Drag the point along the centered-error curve or type k (h = 10⁻ᵏ). Solid and dashed coloured curves are observed errors; purple dashed curves are the documented error budgets.

For sin⁡x\sin x at x=1x=1, the forward difference with h=10−4h=10^{-4} is off by about 4×10−54\times10^{-5} and the centered difference by about 9×10−109\times10^{-10}. Drag toward smaller hh: both errors fall at first, reach a minimum, then rise. At h=10−14h=10^{-14} the forward estimate is wrong in the third digit. Exact algebra says smaller hh is better; floating-point arithmetic disagrees.

Intuition: two errors pulling in opposite directions

A difference quotient replaces a limit by a finite step, which costs truncation error: the secant is not the tangent. Shrinking hh reduces it. But f(x+h)f(x+h) and f(x)f(x) are each rounded to about 16 significant digits; when hh is tiny they agree in most of those digits, their difference keeps only a few correct ones, and dividing by hh magnifies the loss. That rounding error grows as hh shrinks. The total is smallest somewhere in between.

Definition

With step h>0h>0:

D+=f(x+h)−f(x)h,D_+=\frac{f(x+h)-f(x)}{h}, D−=f(x)−f(x−h)h,D_-=\frac{f(x)-f(x-h)}{h}, D0=f(x+h)−f(x−h)2h.D_0=\frac{f(x+h)-f(x-h)}{2h}.

These are the forward, backward and centered differences. Each approximates f′(x)f'(x); their errors are measured here against an independent reference: the analytic derivative (cos⁡x\cos x for sin⁡x\sin x, exe^x for exe^x, and the exact rational x2/2−1x^2/2-1 for the cubic).

Mechanics: what the explorer computes

All quotients are computed in IEEE binary64, exactly as naive code would, dividing by the nominal hh. For each scheme and each k=1,…,16k=1,\dots,16 the plot shows log⁡10\log_{10} of the observed error. The dashed budget curves add the leading truncation term and a rounding term built from machine epsilon ε=2−52\varepsilon=2^{-52} and the sizes of the sampled values. The budgets are explanations and upper-envelope estimates for these smooth functions, not guarantees for arbitrary ff.

Derivation: the two terms and the best step

Taylor’s theorem gives f(x+h)=f(x)+hf′(x)+h22f′′(ξ)f(x+h)=f(x)+hf'(x)+\tfrac{h^2}2f''(\xi), so

D+−f′(x)=h2f′′(ξ),D_+-f'(x)=\tfrac h2f''(\xi),

a truncation error of order hh.

For the centered difference the h2h^2 terms cancel and the error is h26f′′′(η)\tfrac{h^2}6f'''(\eta) — order h2h^2. Each computed value carries a relative rounding error of about ε\varepsilon, so the computed numerator is off by roughly ε(∣f(x+h)∣+∣f(x)∣)\varepsilon(|f(x+h)|+|f(x)|), divided by hh. Minimising

E(h)≈h2∣f′′∣+2ε∣f∣hE(h)\approx\tfrac h2|f''|+\frac{2\varepsilon|f|}{h}

gives h∗≈2ε∣f∣/∣f′′∣h^*\approx2\sqrt{\varepsilon|f|/|f''|}, about 10−810^{-8} for well-scaled ff; for the centered difference h∗≈3ε∣f∣/∣f′′′∣3h^*\approx\sqrt[3]{3\varepsilon|f|/|f'''|}, about 10−510^{-5}.

Worked example

f=sin⁡f=\sin, x=1x=1, f′(1)=cos⁡1≈0.5403023f'(1)=\cos1\approx0.5403023:

  • h=10−1h=10^{-1}: forward error ≈4.3×10−2\approx4.3\times10^{-2}, centered ≈9×10−4\approx9\times10^{-4} — truncation dominates;
  • h=10−4h=10^{-4}: forward ≈4×10−5\approx4\times10^{-5}, centered ≈9×10−10\approx9\times10^{-10};
  • h=10−8h=10^{-8}: forward ≈3×10−9\approx3\times10^{-9}, the best region for forward differences;
  • h=10−14h=10^{-14}: forward ≈4×10−3\approx4\times10^{-3} — rounding has taken over.

Replay the worked derivation

h = 10⁻¹

Forward error 4.29×10⁻² (budget: truncation 5.00×10⁻², rounding 4.30×10⁻¹⁵); centered error 9.00×10⁻⁴.

h=10−1:∣D+−f′∣≈4.29×10−2,∣D0−f′∣≈9.00×10−4h=10^{-1}:\quad |D_+-f'|\approx 4.29\times10^{-2},\quad |D_0-f'|\approx 9.00\times10^{-4}
Replay the errors at h = 10⁻¹, 10⁻⁴, 10⁻⁸, 10⁻¹², 10⁻¹⁶.

When numbers mislead

At h=10−16h=10^{-16}, x+hx+h may round to xx itself, making D+=0D_+=0 — a confident, completely wrong answer. Even the step is inexact: (x+h)−x(x+h)-x is usually not exactly hh in binary64, a representation error the budget includes. For a function with a corner or a jump, no step size gives a meaningful derivative, because none exists (III.3).

Executable reference code

The reference compares the three schemes with an exact derivative of a polynomial evaluated in floating point and in Fraction, isolating rounding error. The NumPy version sweeps h=10−1,…,10−16h=10^{-1},\dots,10^{-16}, finds the empirical best step and compares it with ε\sqrt\varepsilon.

code/python/calculus_finite_difference.py
"""Finite differences of a polynomial: exact rational quotients versus binary64 ones isolate rounding error (III.14)."""
from fractions import Fraction as F

p = lambda x: x**3 / 6 - x                  # works for Fraction and float
dp = lambda x: x**2 / 2 - 1                 # exact derivative

x = F(3, 2)
for k in range(1, 17):
    h = F(1, 10**k)
    exact_forward = (p(x + h) - p(x)) / h          # exact rational quotient
    # In exact arithmetic the forward error is exactly h*x/2 + h**2/6 (truncation only).
    assert exact_forward - dp(x) == h * x / 2 + h * h / 6

xf = 1.5
errs = [abs((p(xf + 10.0**-k) - p(xf)) / 10.0**-k - float(dp(x))) for k in range(1, 17)]
best = min(range(16), key=lambda i: errs[i])
assert 5 <= best + 1 <= 10                # the best step is near sqrt(eps) ~ 1e-8, not the smallest one
assert errs[15] > errs[best] * 100        # h = 1e-16 is far worse than the best step
code/python/calculus_finite_difference_numpy.py
"""Sweep h = 10**-1 ... 10**-16 for sin at 1: forward error is smallest near sqrt(eps), centered near eps**(1/3) (III.14)."""
import numpy as np

x = 1.0
h = 10.0 ** -np.arange(1, 17)
forward = np.abs((np.sin(x + h) - np.sin(x)) / h - np.cos(x))
centered = np.abs((np.sin(x + h) - np.sin(x - h)) / (2 * h) - np.cos(x))
eps = np.finfo(float).eps
assert abs(np.log10(h[np.argmin(forward)]) - np.log10(np.sqrt(eps))) <= 1.5
assert abs(np.log10(h[np.argmin(centered)]) - np.log10(np.cbrt(eps))) <= 1.5
assert centered.min() < forward.min()          # higher order wins at its best step
assert forward[-3] > 100 * forward.min()       # tiny steps are much worse

Explore

Compare eˣ at 2 with sin x: the larger ∣f∣|f|, the larger the rounding term and the earlier the error curve turns up. On the polynomial, the centered difference’s truncation error is tiny; its curve is shaped almost entirely by rounding. Notice where forward and backward errors differ in sign but not in size.

Common mistakes

Choosing hh as small as possible. Using a fixed absolute hh for inputs of very different magnitude (a relative step such as h=εmax⁡(1,∣x∣)h=\sqrt\varepsilon\max(1,|x|) is usual). Trusting a finite-difference check of a gradient without a tolerance that reflects these errors.

Numerical considerations

Complex-step differentiation, Richardson extrapolation and automatic differentiation (III.10) avoid or reduce the cancellation problem. When finite differences are used as a test of AD code, a centered difference with h≈10−5h\approx10^{-5}–10−610^{-6} and a relative tolerance around 10−710^{-7} is a common, defensible choice for smooth functions.

Engineering and ML connections

Gradient checking in machine-learning code compares backpropagation with centered differences. Simulation codes estimate Jacobians by finite differences when no derivative code exists, and must choose step sizes per variable. The same truncation-versus-rounding trade-off appears whenever a continuous limit is replaced by a finite, floating-point computation.

Exercises

calculation

A forward difference

f(x) = x², x = 1, h = 0.1. Compute (f(x+h) − f(x))/h.

calculation

A centered difference

f(x) = x², x = 1, h = 0.1. Compute (f(x+h) − f(x−h))/(2h).

calculation

Error orders

Halving h divides the forward truncation error by about how much, and the centered one by about how much?

prediction

Is smaller h always better?

In binary64, why can h = 10⁻¹⁴ give a worse derivative than h = 10⁻⁸?

Choose one answer

prediction

Choosing h

For the forward difference of a well-scaled f, where is the best h roughly?

Choose one answer

Summary and checkpoints

Forward and backward differences have truncation error of order hh, centered differences of order h2h^2; rounding error grows like ε/h\varepsilon/h. Their sum is minimised near h≈εh\approx\sqrt\varepsilon (forward) or ε3\sqrt[3]\varepsilon (centered), and tinier steps make results worse. Next, III.15 studies the matching question for integrals.

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