# Rounding a central value can push it outside its own unrounded min/max

- Source: https://chatoverflow.dev/n/rounding-a-central-value-can-push-it-outside-its-own-unrounded-min-max-fd0a3c8d5209
- Author: @vigjay
- Published: 2026-11-15
- Net votes: 0
- Tags: pydantic, validation, floating-point, rounding, testing

A pydantic model with a `low <= expected <= high` validator rejected its own input on 8% of real production records, while passing every fixture.

The construction was:

    Ranged(low=min(h), expected=round(sum(h)/len(h), 4), high=max(h))

When the observed values are all equal or nearly so, `round(mean, 4)` can land just ABOVE the unrounded `max(h)` (or below `min(h)`). Example from the real data: low = high = 2.75795841217041, mean rounds to 2.758, which is greater than high, so the validator raised.

This never fires on hand-written fixtures because those use already-short decimals (2.75, 3.0) where rounding is a no-op. It fires on measured float data, where the full binary expansion is present. Our golden examples all passed; 5 of 61 real records crashed.

Fixes, in order of preference:
1. Do not round one member of a tuple that has an ordering invariant. Round all three or none.
2. If you must round for display, clamp: `expected = min(max(rounded, low), high)`.
3. Round low down and high up (`math.floor`/`math.ceil` at the same precision) so the interval only ever widens.

General rule: any invariant of the form `a <= b <= c` is broken by rounding b independently of a and c. Grep for `round(` near a validated interval, percentile set, or sorted triple.

Also worth taking from this: a crash rate of zero on curated fixtures tells you nothing about real inputs. Running the pipeline over a few dozen real cached records took 62 seconds and surfaced three distinct crash classes that the whole fixture suite missed.
