Finite differences
有限差分
Separate derivative truncation error, evaluation noise and floating-point collapse.
finite-differencesEstimate a slope by asking for two nearby values
You can run a loss function but cannot inspect its derivative code. Evaluate it at two nearby inputs, divide the output change by the input change, and you obtain a finite-difference slope estimate. This makes finite differences useful for diagnostics and for functions available only through an evaluator.
There is a catch: making the separation smaller does not improve a floating-point estimate forever. Eventually nearby inputs or outputs become numerically indistinguishable. We will first isolate the mathematical approximation error with exact fractions, then show a tiny floating-point step that returns zero for a nonzero derivative.
Read derivatives, Taylor expansions and floating point first. Finite differences approximate derivatives; they are not automatic differentiation.
Choose the stencil before discussing accuracy
For a positive step h, forward and central differences are:
The evaluation points and weights form a stencil. The forward stencil needs the point and its right neighbor; the central stencil needs both sides. At a domain boundary, the central expression may request an invalid input. NIST DLMF §3.4 develops numerical differentiation formulas and their error terms.
Taylor expansion explains the difference in accuracy. With bounded second derivative near x, forward error is O(h). With a bounded third derivative across the central stencil, the symmetric subtraction cancels the second-order term and gives:
Here M₂ and M₃ bound the corresponding absolute derivatives on the intervals used. These assumptions matter: a central difference at a corner does not manufacture a derivative that does not exist. For f(x)=|x| at zero, the central estimate is zero for every h, although the left and right derivatives disagree.
For f(x)=x³ at x=2, expansion gives the exact forward value 12+6h+h² and central value 12+h². The derivative is 12. Halving h quarters the central truncation error. This identity holds in real arithmetic independently of a computer experiment.
Evaluation error competes with truncation error
Suppose each sampled function value has absolute error at most η. Subtracting two such values can introduce error up to 2η. The central denominator is 2h, so a bound for the combined error is:
This model holds when the stated evaluation-error bound holds; actual floating-point error may also involve perturbed input coordinates. The first term improves as h shrinks, while the second worsens. There is no universal best h independent of scale, smoothness and evaluation accuracy. Python’s floating-point tutorial explains why stored numbers and arithmetic differ from exact reals.
Separate exact truncation error from numerical collapse
The complete Python 3.12 program uses a rational-only helper for its polynomial experiment. It rejects nonpositive steps, unknown methods, booleans and nonrational return values. Each estimate calls the function twice. The final, separate experiment uses ordinary floating-point arithmetic deliberately.
from fractions import Fraction as F
import math
def difference(f,x,h,method='central'):
if type(x) not in (int,F) or type(h) not in (int,F) or h <= 0:
raise ValueError('rational x and positive rational h required')
if method not in ('forward','central'):
raise ValueError('unknown difference method')
x,h=F(x),F(h)
points=(x+h,x) if method=='forward' else (x+h,x-h)
values=[f(v) for v in points]
if any(type(v) not in (int,F) for v in values):
raise ValueError('function must return rational values')
return (F(values[0])-F(values[1]))/(h if method=='forward' else 2*h)
if __name__ == '__main__':
for h in [F(1,2),F(1,4),F(1,8)]:
forward=difference(lambda x:x**3,2,h,'forward')
central=difference(lambda x:x**3,2,h)
assert forward==12+6*h+h*h and central==12+h*h
print('h='+str(h),'forward error='+str(forward-12),
'central error='+str(central-12))
h=1e-16
estimate=(math.exp(1.0+h)-math.exp(1.0))/h
print('floating-point input collapsed:',1.0+h==1.0)
print('floating-point forward estimate:',estimate)
print('true derivative is exp(1), approximately:',round(math.exp(1),6))
Recorded output:
h=1/2 forward error=13/4 central error=1/4
h=1/4 forward error=25/16 central error=1/16
h=1/8 forward error=49/64 central error=1/64
floating-point input collapsed: True
floating-point forward estimate: 0.0
true derivative is exp(1), approximately: 2.718282
The central errors are 1/4,1/16,1/64, exactly as the cubic expansion predicts. In the floating-point example, 1+10⁻¹⁶ rounds to 1, so the two exponential calls receive identical inputs. Dividing their zero difference by h gives zero, not exp(1). This is a representation failure, not a new property of the exponential derivative.
For a d-coordinate scalar objective, independently applying a central stencil to each coordinate takes 2d function evaluations. A directional derivative takes two evaluations along a chosen vector. Costs depend mainly on the evaluator, which may be a whole model run; caching and parallelism change engineering cost, not the stencil’s mathematical meaning.
The evaluator must represent the same function twice
Random augmentation, sampling or mutable state can make the two calls describe different functions. A noisy difference divided by a small h can explode. Fix the experimental state when appropriate, or use a method designed for stochastic evaluations and report its uncertainty.
Higher-order stencils use more points and stronger smoothness assumptions; they can amplify noise. Complex-step differentiation avoids one subtraction for suitable analytic implementations, but it requires a function that supports the needed complex extension. It is not a drop-in solution for comparisons, absolute values or arbitrary black-box code.
Finite differences are particularly useful as a small-scale check of analytic or automatically differentiated gradients. They are not exact ground truth. Compare several sensible step sizes and examine absolute and relative discrepancies, as discussed in gradient checking.
Ask which error changed
- What is the central estimate for x³ at x=2 with h=1/4?
Answer 1: 12+1/16=193/16. Its truncation error is 1/16.
- Why does a zero central difference for |x| at zero not prove differentiability?
Answer 2: The stencil averages incompatible one-sided slopes. The left derivative is −1 and the right derivative is 1; there is no derivative at the point.
- Under the bounded evaluation-error model, what happens to η/h when h is halved?
Answer 3: It doubles. A smaller step can reduce truncation error while increasing evaluation-error amplification.
- Why does the exponential example return zero with h=10⁻¹⁶?
Answer 4: The stored inputs 1+h and 1 are equal, so both calls return the same value. The requested mathematical displacement did not survive representation.
Use approximation as a diagnostic instrument
DLMF provides differentiation stencils and error analysis; Python’s tutorial supplies the representation context. The exact cubic and collapsed-input examples distinguish two different failure mechanisms rather than ranking methods by one lucky step size.
As a project, perturb a single model parameter over a range of steps, plot the discrepancy against an analytic derivative, and identify where truncation, noise or rounding dominates. Keep the evaluator deterministic for that diagnostic, and separately investigate any stochastic behavior.
Make a prediction, then check
Does an arbitrarily small floating-point step always improve a derivative estimate?
Learning objectives
- Derive first- and second-order stencil errors.
- Explain why shrinking a step can worsen an estimate.
Prerequisites & connections
Explore related knowledge →References
- DLMF §3.4 — Differentiation
NIST Digital Library of Mathematical Functions - Floating-Point Arithmetic: Issues and Limitations — Python 3.12
Python Software Foundation
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, derivations, exact/literal and numerical checks, and bilingual review; not independent human or second-agent peer review.
- Single-agent authored technical review: primary-source locations, explicit domains and assumptions, derivations, literal/exact probability or numerical reference cases, bilingual examples and exercises. Not independent human or second-agent review.
- Four focused tests passed on CPython3.12.4; NumPy1.26.4 actually executed for the Fourier chapter. Exact rational probability/stencil checks are distinguished from floating-point calculations and observed Monte Carlo output. Both languages render three equations, six anchors and four answers; final repository checks recorded separately.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- DLMF §3.4 — Differentiation · §3.4 numerical differentiation: finite-difference formulas and errors; bounds rederived from Taylor expansions.
- Floating-Point Arithmetic: Issues and Limitations — Python 3.12 · Python3.12 tutorial: representational rounding and arithmetic error; actual binary64 input-collapse experiment.
Related topics