Numerical Accuracy and Stability
A correct mathematical formula can produce an inaccurate result on a computer. Floating point numbers have finite precision and a finite range. Numerical methods must account for both limits.
Read logarithms, linear algebra, and likelihood first.
Decimal fractions are not always exact
Section titled “Decimal fractions are not always exact”Binary floating point cannot represent every decimal fraction exactly. Arithmetic therefore rounds many intermediate values. Exact equality can fail even when two expressions describe the same real number.
import numpy as np
computed = 0.1 + 0.2print("Computed value:", repr(computed))print("Exact equality:", computed == 0.3)print("Absolute difference:", f"{abs(computed - 0.3):.3e}")print("Agreement within tolerance:", np.isclose(computed, 0.3))Computed value: 0.30000000000000004Exact equality: FalseAbsolute difference: 5.551e-17Agreement within tolerance: TrueChoose tolerances from the scale and purpose of the calculation. An absolute tolerance controls differences near zero. A relative tolerance scales with the reference magnitude. Default tolerances are not a scientific acceptance criterion for every measurement.
Consider a small positive value compared with zero. A default absolute tolerance may classify it as close to zero even when the application needs to distinguish the two. Explicit tolerances make that decision visible.
small_measurement = 1e-9print("Default comparison with zero:", np.isclose(small_measurement, 0.0))print("Absolute tolerance 1e-12:", np.isclose(small_measurement, 0.0, rtol=0.0, atol=1e-12))Default comparison with zero: TrueAbsolute tolerance 1e-12: FalseNeither tolerance is universally correct. The acceptable discrepancy depends on the units, the measurement process, and the use of the result. An absolute tolerance that makes sense for concentrations in one unit may be inappropriate after a unit conversion.
Products can underflow
Section titled “Products can underflow”A product of many positive probabilities can become too small to represent. The computer then stores zero. Adding log probabilities preserves useful information across a much wider range.
probabilities = np.full(2000, 0.5)ordinary_likelihood = probabilities.prod()log_likelihood = np.log(probabilities).sum()print("Ordinary likelihood:", ordinary_likelihood)print(f"Log likelihood: {log_likelihood:.4f}")assert ordinary_likelihood == 0.0assert np.isfinite(log_likelihood)Ordinary likelihood: 0.0Log likelihood: -1386.2944The mathematical product is positive. The stored zero is a representational limit, not evidence that the model makes the data impossible. Exponentiating the final log likelihood can underflow again, so retain logs for comparisons.
Normalize in log space
Section titled “Normalize in log space”When several log weights are large in magnitude, subtracting their log sum gives normalized log weights. The log sum exp operation evaluates that sum without directly exponentiating the original large or small values.
from scipy.special import logsumexp
log_weights = np.array([-1000.0, -1001.0, -1002.0])naive_weights = np.exp(log_weights)normalized = np.exp(log_weights - logsumexp(log_weights))print("Direct exponentials:", naive_weights)print("Normalized weights:", np.round(normalized, 6))print(f"Weight sum: {normalized.sum():.6f}")assert np.isclose(normalized.sum(), 1.0)Direct exponentials: [0. 0. 0.]Normalized weights: [0.665241 0.244728 0.090031]Weight sum: 1.000000This calculation normalizes the supplied weights. Calling them posterior probabilities would require a model that includes the appropriate likelihoods and priors.
Preserve small differences
Section titled “Preserve small differences”Adding a tiny number to one can round back to one. A subsequent logarithm then loses the tiny change. log1p(x) calculates log(1+x) accurately near zero. expm1(x) serves the corresponding role for exp(x)-1.
small = 1e-16print(f"Direct log: {np.log(1.0 + small):.3e}")print(f"log1p: {np.log1p(small):.3e}")print(f"Direct exponential difference: {np.exp(small) - 1.0:.3e}")print(f"expm1: {np.expm1(small):.3e}")Direct log: 0.000e+00log1p: 1.000e-16Direct exponential difference: 0.000e+00expm1: 1.000e-16For a small upper-tail probability, a distribution’s survival function can also preserve accuracy better than subtracting its cumulative probability from one.
Some problems amplify input error
Section titled “Some problems amplify input error”An ill-conditioned problem is sensitive to small input changes. A stable solver cannot remove that sensitivity. A nearly dependent pair of columns makes a linear system a useful example.
system = np.array([[1.0, 1.0], [1.0, 1.000001]])observed = np.array([2.0, 2.000001])perturbed = observed + np.array([0.0, 0.000001])solution = np.linalg.solve(system, observed)changed_solution = np.linalg.solve(system, perturbed)print(f"Condition number: {np.linalg.cond(system):.3e}")print("Original solution:", np.round(solution, 4))print("Perturbed solution:", np.round(changed_solution, 4))print("Reconstructs perturbed input:", np.allclose(system @ changed_solution, perturbed))Condition number: 4.000e+06Original solution: [1. 1.]Perturbed solution: [-0. 2.]Reconstructs perturbed input: TrueThe tiny input perturbation changes the solution substantially. A small reconstruction residual therefore does not prove that the estimated coefficients are accurate. Measurement uncertainty and matrix conditioning both matter.
Separate three sources of disagreement. Measurement uncertainty concerns how well the inputs describe the experiment. Model error concerns whether the equations describe the relevant biology. Numerical error concerns how accurately the computer evaluates the chosen calculation.
Increasing floating point precision can reduce some numerical errors. It does not supply missing biological replicates or remove a systematic measurement bias. Conversely, a well-designed experiment can still suffer from an unstable numerical calculation.
Check your understanding
Section titled “Check your understanding”Why is a very negative finite log likelihood different from an ordinary likelihood stored as zero?
The finite log value preserves a magnitude that can still be compared with other log likelihoods. The underflowed zero loses that information. If several different positive likelihoods all underflow, their stored zeros cannot establish their relative support.
Further reading
Section titled “Further reading”-
Python floating point tutorial
The tutorial explains binary representation, rounding, and comparison. Its examples distinguish displayed precision from stored precision.
-
Fundamentals of Numerical Computation on conditioning
The chapter develops sensitivity to input errors and condition numbers. Compare those definitions with the nearly singular mixture matrix.
The SciPy logsumexp reference describes the stable operation. Use the statistical analysis guides to apply these foundations to experimental data, or the machine learning guides to fit and evaluate predictive models.