Numerical stability
数值稳定性
Compare equivalent formulas, distinguish backward from forward error, and diagnose cancellation with independent high-precision references.
numerical-stabilityAn algebraically correct formula can lose the answer
How much bigger is than one when ? The answer is close to . A direct binary64 calculation of sqrt(1+x)-1 can return zero: 1+x has already rounded to one. The subtraction exposes information lost earlier.
Multiply numerator and denominator by the conjugate, and the same mathematical function becomes
The right side keeps the small quantity x in the numerator and divides it by a number near two. It produces a useful answer in the regime where the direct formula failed. This example concerns the computation chosen for a fixed function, which is the focus of numerical stability. Goldberg, Cancellation
Ask which error you are measuring
For an intended problem y=f(x) and computed answer , the forward error compares the answer with the true output. A backward-error question instead asks how much the input would need to change to make the computed answer exact:
If no admissible perturbed input produces the answer, that backward error is infinite. Relative versions divide by appropriate nonzero input or output norms; structured problems may restrict which perturbations are allowed. “Backward stable” normally means the method solves a nearby problem with a small relative perturbation, typically bounded by modest dimension-dependent factors times the arithmetic unit roundoff.
Higham, What is Numerical Stability?
A small backward error does not guarantee a small forward error if the problem amplifies input changes. Locally, for a differentiable scalar f with nonzero x and f(x), first-order expansion yields
The coefficient is a condition number for this input/output choice. Stability concerns the algorithm; conditioning concerns sensitivity of the problem. Increasing precision can reduce arithmetic perturbations, but does not remove uncertainty already present in measured inputs.
For the square-root increment, at nonzero x greater than −1, rationalization gives the relative condition number , which tends to one as x tends to zero. The underlying problem is well conditioned in that regime. Losing the answer there is a flaw in the direct evaluation route, not unavoidable sensitivity. At exactly zero, the relative output error is undefined; use an absolute error.
Use a separate numerical reference
This complete example compares both formulas with an 80-digit Decimal computation. Decimal.from_float deliberately starts from the same stored binary input, isolating evaluation error from decimal-input conversion. The reference is much higher precision, not symbolic exact arithmetic. The test region is moderate and explicitly listed.
import math
from decimal import Decimal, localcontext
def sqrt_increment(x):
if not math.isfinite(x) or x < -1:
raise ValueError("finite x >= -1 required")
return x/(math.sqrt(1+x)+1)
def relative_error(value, reference):
if reference == 0:
raise ValueError("relative error needs a nonzero reference")
return abs((Decimal.from_float(value)-reference)/reference)
with localcontext() as ctx:
ctx.prec = 80
for x in [1e-8,1e-12,1e-16,-1e-12,.2]:
d = Decimal.from_float(x)
ref = (1+d).sqrt()-1
stable = sqrt_increment(x)
assert relative_error(stable,ref) < Decimal('5e-16')
x = 1e-16
reference = (1+Decimal.from_float(x)).sqrt()-1
assert math.sqrt(1+x)-1 == 0.
assert relative_error(math.sqrt(1+x)-1,reference) == 1
assert sqrt_increment(x) > 0
assert sqrt_increment(-1.) == -1.
assert math.log(1+1e-16) == 0.
assert math.log1p(1e-16) > 0.
assert math.expm1(1e-16) > 0.
Both scalar formulas take constant arithmetic work, but their errors differ. The 80-digit reference costs more per operation than binary64. A test against the same formula at the same precision could share the same error, so it would be weaker evidence. For a production routine, test near domain boundaries and over the required magnitude range as well as checking these examples.
Cancellation is a clue, not a universal diagnosis
Subtracting nearby exact floating-point operands can be exact; cancellation does not necessarily introduce new rounding in that subtraction. The danger is that it can reveal large relative error inherited from previous operations or input approximations. Adding a small value to a large one can also lose information without a subtraction at all.
Specialized functions preserve information around delicate points: log1p(x) evaluates near zero, and expm1(x) evaluates there. Replacing them with the literal compound expressions can throw away useful digits. Their domain and overflow rules still apply. Python math documentation
In probability calculations, taking exp first can underflow or overflow before a later logarithm would bring the answer back into range. Work in log space where appropriate and use stable normalization. A stable softmax can still produce numerically zero probabilities for extremely unfavorable finite logits; directly calculating log probabilities avoids taking the logarithm of those rounded zeros. Deep Learning, Section 4.1
There is no single rewrite that makes an entire training system stable. Inspect the first nonfinite value, operand magnitudes, reduction order, precision, and scaling. Clipping every nonfinite output to a constant may hide the cause while changing the model. A residual check is useful, but on a poorly conditioned solve it may coexist with a large solution error.
Identify the failure before fixing it
- At , where does the direct square-root increment first lose information? Answer: forming rounds away x before the square root and subtraction.
- Does the rationalized expression recover an x that was rounded to zero before entering the function? Answer: no. It preserves the input it receives, not unknown original measurements.
- Why compare Decimal values from the exact stored float? Answer: to test evaluation error without mixing in a different input-conversion error.
- If the answer is exact for a slightly changed input, must it be close to the original answer? Answer: only if the problem is sufficiently well conditioned for that perturbation.
Use stability as an engineering question
A useful bug report includes the formula, dtype, input range, first failing operation, and an independently computed reference. This makes a claim of improved stability testable. The conditioning article develops sensitivity bounds for linear systems; log-sum-exp shows a reusable stabilization method with explicit edge-case behavior.
Make a prediction, then check
If sqrt(1+x)−1 returns zero at x=10⁻¹⁶, where is information first lost?
Learning objectives
- Locate and reduce information loss from cancellation through equivalent reformulations.
- Distinguish forward error, backward error, and problem sensitivity.
Prerequisites & connections
Explore related knowledge →References
- What Every Computer Scientist Should Know About Floating-Point Arithmetic — Oracle edited reprint
David Goldberg · 1991 - Python — math: Mathematical functions
Python Software Foundation - Deep Learning — Chapter 4: Numerical Computation
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - What is Numerical Stability?
Nicholas J. Higham · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: specified-source comparison, derivation checks, independent numerical checks, and paragraph-level bilingual comparison; no independent human peer review.
- Compared the square-root increment with 180-digit Decimal for 76 boundary and cross-scale inputs, starting from exact stored floats to isolate evaluation error.
- Derived the square-root increment condition-number limit and separated evaluation loss from input sensitivity; finite high-precision checks are not presented as global symbolic proof.
- Compared bilingual assumptions, claims, numbers, exercise answers and citations; structural checks additionally compare formulas, code, main anchors and source IDs.
Source locations checked:
- What Every Computer Scientist Should Know About Floating-Point Arithmetic — Oracle edited reprint · Cancellation: benign/catastrophic distinction and subtraction exposing earlier rounding
- Python — math: Mathematical functions · log1p and expm1 contracts
- Deep Learning — Chapter 4: Numerical Computation · §4.1, softmax shifting and directly computed log probabilities
- What is Numerical Stability? · Definitions of forward/backward error, backward stability, data and norm conventions
Related topics