Comparing Floating-Point Values with Tolerances

A tolerance expresses how much difference a calculation or measurement can permit at the scale of the problem.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use two scales
  2. Check two plausible results
  3. Work at two values of different scale
  4. Check that the tolerance can reject a real defect

Use two scales

A common closeness rule tests \(|a-b|\le\max(t_{\rm rel}\max(|a|,|b|),t_{\rm abs})\). The absolute term helps near zero. The relative term grows with the magnitude of the operands. Review binary rounding before setting tolerances close to the resolution of the representation.

Check two plausible results

With relative tolerance \(10^{-3}\), 1000 and 1000.5 are close. With absolute tolerance 0.001, zero and 0.0005 are close even though their relative difference is large. Choose the absolute value in the same unit as the quantity, following unit-aware naming.[1]

Work at two values of different scale

Suppose two calculations of a length give 50.0002 meters and 50.0000 meters. Their absolute difference is 0.0002 meters and the relative difference compared with fifty is about four parts per million. A tolerance of one millimeter accepts the pair. Now compare 0.0002 meters with zero. The same absolute tolerance accepts it, while a relative comparison alone can be unsuitable at zero. Choose thresholds from the feature's expected scale and the maximum error users can tolerate. See absolute and relative error.

Check that the tolerance can reject a real defect

An overbroad tolerance might accept an implementation returning meters where centimeters were required. Include a deliberately wrong value that should fail, as well as two expected nearby results. If the mathematical answer should be exactly one of a handful of discrete values, a tolerance might be the wrong assertion.

Also set aside behavior for infinities or missing numbers according to the language and domain. NaN comparisons are special in common floating-point models. When such values should be rejected, check their presence explicitly instead of quietly treating them as just a large numerical error. Numeric test tolerances connect these choices to regression checks.

References

  1. Python Software Foundation, Python Tutorial: Floating-Point Arithmetic ↩