Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ releases are available on [Anaconda.org](https://anaconda.org/conda-forge/ttsim)

## Unreleased

- {gh}`159` Make `RoundingSpec` robust to floating-point representation error: a
quotient `out / base` within 4 ulps of a whole number, and at most a tenth of a base
unit away from it, counts as that whole number before `ceil`, `floor` or `round`, so
`0.0656 * 40000` (2623.9999999999995 in float64) rounds down to 2624, not 2623.
({ghuser}`MImmesberger`)

## v1.3.1 — 2026-09-02

- {gh}`154` Make `BooleanLevel` a frozen dataclass so beartype's package claw can
Expand Down
39 changes: 29 additions & 10 deletions src/ttsim/tt/rounding.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@
)


#: Distance to the nearest whole base, in units of the dtype's machine epsilon times
#: the magnitude, below which a quotient counts as that whole base. A product or
#: quotient of two decimal operands lands within about one ulp of its exact value;
#: anything much looser swallows genuine fractions in float32 (16 ulps of 12 290 are
#: 0.023, and 0.204833 * 60000 = 12289.98 would round up to 12290).
_SNAP_TOLERANCE_IN_ULPS = 4

#: Upper bound on that distance in base units. In float32 a few ulps of a large
#: quotient are a sizeable part of a base unit (16 ulps of 181 417 are 0.35), so
#: without the bound a quotient a third below a whole base would be snapped up to it.
_SNAP_TOLERANCE_MAX_IN_BASE_UNITS = 0.1


@beartype(conf=ROUNDING_SPEC_CONF)
@dataclass(frozen=True)
class RoundingSpec:
Expand Down Expand Up @@ -72,16 +85,22 @@ def apply_rounding(

@functools.wraps(func, assigned=_WRAPPER_ASSIGNMENTS_NO_ANNOTATIONS)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> FloatColumn:
out = func(*args, **kwargs)

if self.direction == "up":
rounded_out = self.base * xnp.ceil(out / self.base)
elif self.direction == "down":
rounded_out = self.base * xnp.floor(out / self.base)
else: # self.direction == "nearest"
rounded_out = self.base * (xnp.asarray(out) / self.base).round()

return rounded_out + self.to_add_after_rounding
# Snap near-whole quotients so representation error cannot flip a
# directed rounding (0.0656 * 40000 is 2623.9999999999995 in float64).
scaled = xnp.asarray(func(*args, **kwargs)) / self.base
nearest = xnp.round(scaled)
tolerance = xnp.minimum(
_SNAP_TOLERANCE_IN_ULPS
* xnp.finfo(scaled.dtype).eps
* xnp.maximum(xnp.abs(scaled), 1.0),
_SNAP_TOLERANCE_MAX_IN_BASE_UNITS,
)
scaled = xnp.where(xnp.abs(scaled - nearest) <= tolerance, nearest, scaled)
round_func = {"up": xnp.ceil, "down": xnp.floor, "nearest": xnp.round}
return (
self.base * round_func[self.direction](scaled)
+ self.to_add_after_rounding
)

# Synthesise the typed outer forwarder. Inputs mirror the wrapped
# function's signature; the return is always `FloatColumn` because
Expand Down
38 changes: 38 additions & 0 deletions tests/tt/test_rounding.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,40 @@ def p_id() -> int:


rounding_specs_and_exp_results = [
# Products whose exact decimal value is a whole number land one ulp below or above
# it in binary floating point; directed rounding must not drop or add a whole base.
(
RoundingSpec(base=1, direction="down"),
numpy.array([1e-6 * 65600 * 40000, 2623.5]),
numpy.array([2624.0, 2623.0]),
),
(
RoundingSpec(base=1, direction="down"),
numpy.array([1e-6 * 65600 * 3_000_000_000, 196_800_000.5]),
numpy.array([196_800_000.0, 196_800_000.0]),
),
(
RoundingSpec(base=1, direction="up"),
numpy.array([0.07 * 100, 7.5]),
numpy.array([7.0, 8.0]),
),
(
RoundingSpec(base=1e-6, direction="up"),
numpy.array([0.0656, 0.0731355]),
numpy.array([0.0656, 0.073136]),
),
# In float32, 13062 / 72000 / 1e-6 is 181416.66 and 0.204833 * 60000 is 12289.98;
# a few ulps there are a visible part of a base, so neither may be carried up.
(
RoundingSpec(base=1e-6, direction="down"),
numpy.array([13062 / 72000, 0.0656]),
numpy.array([0.181416, 0.0656]),
),
(
RoundingSpec(base=1, direction="down"),
numpy.array([0.204833 * 60000, 2624.0]),
numpy.array([12289.0, 2624.0]),
),
(
RoundingSpec(base=1, direction="up"),
numpy.array([100.24, 100.78]),
Expand Down Expand Up @@ -141,11 +175,15 @@ def test_func(x: float) -> float:
backend=backend,
unit_system=TEST_UNIT_SYSTEM,
)
# A snap that lands on the wrong base is one base unit off, which the default
# relative tolerance would hide for large quotients.
assert_series_equal(
pd.Series(results__tree["namespace"]["test_func"]),
pd.Series(exp_output),
check_names=False,
check_dtype=False,
rtol=1e-7,
atol=0,
)


Expand Down
Loading