skip to content

When comparing two floats in game code, how do absolute epsilon, relative epsilon and ULP-distance comparisons differ, and where does each fail?

level: middleimportance: should knowfreq 42%

answer

  1. the gap between floats grows
  2. fixed tolerance versus scaled tolerance
  3. bit patterns read as ordered integers
  4. near zero, scaled tests collapse
  5. subtracting near-equal values loses digits

basics

~20 s

An absolute epsilon fails for large values, where neighbouring floats are farther apart than it; a relative epsilon and a ULP distance fail near zero. Robust code combines an absolute floor with a relative tolerance.

solid answer

~50 s

An **absolute** test, `abs(a - b) <= eps`, works at one scale only: in single precision neighbouring floats near 20,000 are about 0.002 apart, so `eps = 1e-5` there is exact equality, while near 1e-6 it calls values nine times apart equal. A **relative** test, `abs(a - b) <= rel * max(abs(a), abs(b))`, scales with magnitude but breaks near zero, where comparing a computed `1e-9` with `0` passes only if `rel >= 1`. A **ULP** test reads the bit patterns as ordered integers and counts the representable floats between the values; it is scale-free but also fails near zero and across the sign, since `1e-9` is hundreds of millions of ULPs from `0`. So I combine an absolute floor with a relative tolerance and size the floor from **catastrophic cancellation**: a difference of near-equal values carries an error sized by the inputs, not by the result.

code

pseudocode · 12 lines
pseudocode
function nearlyEqual(a, b, absEps, relEps):
    diff = abs(a - b)
    if diff <= absEps:
        return true
    largest = max(abs(a), abs(b))
    return diff <= largest * relEps

// single precision, absEps = 0.000001, relEps = 4 * 2^-23 (about 4.8e-7)
nearlyEqual(0.000000001, 0.0, ...)   // diff 1e-9 <= absEps: true
nearlyEqual(20000.0, 20000.002, ...) // 20000.002 is stored as 20000.001953125;
                                     // diff 0.00195 > absEps, but
                                     // <= 20000.002 * 4.8e-7 (about 0.0095): true

go deeper

for a junior

Recall that the spacing between floats grows with magnitude, so a fixed epsilon cannot fit both tiny and huge values.

for a middle

Explain each comparison's formula and its failure region: absolute fails large, relative and ULP fail near zero, and why a combined test with an absolute floor works.

for a senior

Size tolerances from the inputs of the computation, spot cancellation in geometry code, and rewrite formulas or subtract at small magnitudes instead of loosening epsilons.

for a principal

Standardise one comparison helper with per-system documented tolerances so physics, gameplay and tools stop inventing their own epsilons.

## The gap between floats is not constant A float keeps a fixed number of significant bits, so the distance between one representable value and the next, one **unit in the last place** (ULP), doubles with every power of two. In single precision: | magnitude | gap to the next float | |---|---| | 1.0 | about 1.2e-7 | | 1,000 | about 6.1e-5 | | 20,000 | about 0.00195 | | 100,000 | about 0.0078 | | 100,000,000 | 8 | Every comparison strategy is an attempt to pick "close enough" against this sliding scale. Two values that are one ULP apart near 1.0 differ by about a ten-millionth; two values one ULP apart near 100,000 differ by nearly 8 mm in metres. A tolerance is only meaningful when it is stated against the scale of the numbers it will meet. ## Absolute epsilon `abs(a - b) <= eps` treats the tolerance as a fixed distance. - It is right when the values have a **known scale**: positions in a small arena, normalised vectors, angles in radians. - It fails for **large values**: near 20,000 the smallest nonzero difference two single-precision values can have is about 0.002, so an `eps` of `1e-5` accepts only bit-identical values. - It fails for **tiny values**: with `eps = 1e-5`, `1e-6` and `9e-6` compare equal although one is nine times the other. ## Relative epsilon `abs(a - b) <= rel * max(abs(a), abs(b))` scales the tolerance with the operands, with `rel` typically a few multiples of the machine epsilon (`2^-23` in single precision). - It handles **large values** correctly, because the tolerance grows with them. - It fails **near zero**: comparing a computed `1e-9` with an expected `0` needs `1e-9 <= rel * 1e-9`, which only holds for `rel >= 1`, a tolerance that accepts anything. ## ULP distance IEEE 754 orders positive floats the same way as their bit patterns read as integers, so subtracting the integer forms of two positive floats counts the representable values between them. - It is **scale-free**: "within 4 ULPs" means the same relative closeness at any magnitude. - Negative values need a mapping first, because the sign bit makes the raw integers run backwards; `+0.0` and `-0.0` have different patterns although they compare equal; NaN must be rejected before counting. - It fails **near zero** exactly like the relative test: in single precision `1e-9` is about 814 million ULPs from `0`, because there are that many tiny floats in between. ## Catastrophic cancellation: why near zero matters Values near zero are often the result of subtracting two large, nearly equal numbers, and that subtraction is where precision disappears. The subtraction itself is exact or nearly so; what it exposes is the rounding already present in the inputs. Store `20000.001` in single precision and it becomes `20000.001953125`, the nearest float, so `20000.001 - 20000.0` evaluates to `0.001953125`, nearly double the true `0.001`. The **absolute** error is still about one ULP of the inputs, but the **relative** error of the result is about 95 percent. This tells you how to size an absolute floor: it must cover a few ULPs of the **largest operand that went into the computation**, not of the result. It also suggests fixes in the computation itself: 1. Subtract early, at small magnitudes: compute positions relative to a nearby reference instead of subtracting two world-space coordinates late. 2. Rearrange formulas: `a*a - b*b` is better computed as `(a - b) * (a + b)`, which avoids subtracting two large squares. 3. Prefer formulations that test a sign or a threshold instead of an equality to zero. ## A combined recipe ``` function nearlyEqual(a, b, absEps, relEps): diff = abs(a - b) if diff <= absEps: // covers values at or near zero return true largest = max(abs(a), abs(b)) return diff <= largest * relEps // covers large values ``` - Choose `absEps` from the scale of the inputs, for example a world-space tolerance such as `1e-4` metres for geometry near the origin. - Choose `relEps` as a few machine epsilons for the precision in use. - Document both per system; a physics tolerance and a UI tolerance are not the same number. - Above all, prefer comparisons that never need equality: `>=` against a threshold, a sign test, or an integer counter.

  • How do you count the ULP distance between two floats that have opposite signs?
    Map each bit pattern to an integer that increases monotonically across the whole float line: keep positive patterns as they are and map negative ones to their negated magnitude, so -0.0 and +0.0 both become 0. The difference of the mapped integers then counts the floats between the two values. Reject NaN first, since it has no position on that line.
  • Why is a*a - b*b inaccurate when a and b are close, and what is the fix?
    Each square is rounded to the precision of its own large magnitude, and subtracting two nearly equal squares cancels the leading digits, leaving mostly those rounding errors. Computing (a - b) * (a + b) subtracts the original values first, which is exact or nearly so for close values, then multiplies, so only one or two small relative errors remain.

  • One absolute epsilon such as 0.00001 is safe for every float comparison.
  • A relative tolerance handles comparisons against zero as well as any other value.
  • ULP distance works everywhere because it is independent of scale.
  • Subtracting two nearly equal floats is where the rounding error is created.
  • Machine epsilon is the right tolerance for comparing any two computed values.