9.17 Tolerance-based numerical tests
For reference value \(r\) and observed value \(x\), a common combined criterion is
where \(a\) is absolute tolerance and \(b\) relative tolerance. Absolute tolerance controls near zero; relative tolerance scales with magnitude.
Choose tolerances from the method
- Closed-form/analytic unit tests can often use near-machine precision.
- ODE predictions need bounds tied to RTOL/ATOL and accumulated propagation.
- Matrix inverses need residual/condition-aware checks rather than elementwise equality alone.
- Statistical tails need relative or log-probability checks.
- Monte Carlo estimators need sampling-error acceptance, while fixed-stream regression tests can use exact values.
Invariants
Add properties that do not require a single reference number: covariance symmetry/PSD, probabilities in [0,1], monotone CDFs, antithetic negation, mass balance, finite objectives and thread-count identity.
Golden files
Golden outputs are valuable when version/hash and stable formatting are frozen. Keep small human-reviewable fixtures and regenerate only after explaining every change. Pair them with independent formulas so a coordinated implementation/output bug is less likely to self-validate.
Failure triage
When a test fails, report absolute error, relative error, threshold, conditioning, platform and relevant settings. Do not print only “expected approximately.” Plot error versus time, dimension or tolerance to distinguish bias from roundoff.
Common mistakes
- Using only relative tolerance at a zero reference.
- Widening a tolerance until a regression passes.
- Testing stochastic estimates without accounting for sampling error.
Checklist
- Predefine absolute and relative thresholds.
- Add mathematical invariants and negative tests.
- Retain detailed failure diagnostics.
Further reading
See floating-point differences, the worked experiment and Chapter 42's planned release validation.