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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased

- Keep finite results in `remap` when an intermediate float product overflows
or rounds to zero. Mapping `1e200` or `1e-200` from a range back to itself
now returns the original value instead of infinity or zero. Ordinary float
rounding, integer floor division and Decimal arithmetic are unchanged.

## 4.2.2 - 2026-11-13

- Format naive datetimes outside the platform's timestamp range in
Expand Down
90 changes: 90 additions & 0 deletions _python_utils_tests/test_converters.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Tests for the conversion helpers in ``python_utils.converters``."""

import decimal
import math
import re
from fractions import Fraction

import pytest

Expand Down Expand Up @@ -102,3 +104,91 @@ def test_scale_1024_accepts_number_without_lt() -> None:
"""Keep the 4.1.4 float path for a type without ``__lt__``."""
value: _LessEqualOnly = _LessEqualOnly(2048)
assert converters.scale_1024(value, 9) == (2.0, 1) # type: ignore[arg-type]


@pytest.mark.parametrize(
'value,old_min,old_max,new_min,new_max',
[
(1e200, 0.0, 1e200, 0.0, 1e200),
(-1e200, 0.0, 1e200, 0.0, 1e200),
(2e200, 1e200, 3e200, 4e200, 8e200),
(2e200, 3e200, 1e200, 8e200, 4e200),
(1e-200, 0.0, 1e-200, 0.0, 1e-200),
(-1e-200, 0.0, 1e-200, 0.0, 1e-200),
(2e-200, 1e-200, 3e-200, 4e-200, 8e-200),
(2e-200, 3e-200, 1e-200, 8e-200, 4e-200),
(0.1, 0.0, 5e-324, 0.0, 5e-324),
(5e-324, 0.0, 5e-324, 0.0, 0.1),
(1e308, 0.0, 1e308, 0.0, 2.0),
(2.0, 0.0, 1e308, 0.0, 1e308),
(5e-324, 0.0, 0.66, 0.0, 0.3),
(5e-324, 0.0, 1 / 1.4, 0.0, 0.4),
(5 * math.ulp(0.0), 0.0, 0.3, 0.0, 0.03),
],
)
def test_remap_extreme_float_product(
value: float,
old_min: float,
old_max: float,
new_min: float,
new_max: float,
) -> None:
"""Keep a representable result when the intermediate product is not."""
v, lo, hi, out_lo, out_hi = map(
Fraction, (value, old_min, old_max, new_min, new_max)
)
expected = float((v - lo) * (out_hi - out_lo) / (hi - lo) + out_lo)
result = converters.remap(value, old_min, old_max, new_min, new_max)
# An absolute tolerance would let zero pass for the tiny expected values.
assert result == pytest.approx(expected, rel=1e-14, abs=0.0)


def test_remap_preserves_normal_float_rounding() -> None:
"""Keep multiplication before division when the product is usable."""
assert converters.remap(0.1, 0.0, 3.0, 0.0, 7.0) == 0.23333333333333336
assert converters.remap(0.0, 0.0, 1.0, 0.0, 1.0) == 0.0


def test_remap_preserves_integer_arithmetic() -> None:
"""Keep floor division and integers larger than a float can hold."""
assert converters.remap(1, 0, 3, 0, -10) == -4
large = 10**400
result = converters.remap(large, 0, large, 0, large)
assert result == large
assert type(result) is int


@pytest.mark.parametrize('value', ['1e200', '1e-200'])
def test_remap_preserves_decimal_arithmetic(value: str) -> None:
"""Keep Decimal promotion and precision outside the float fallback."""
number = decimal.Decimal(value)
result = converters.remap(number, 0.0, number, 0.0, number)
assert result == number
assert isinstance(result, decimal.Decimal)


@pytest.mark.parametrize(
'value,old_min,old_max,new_min,new_max,expected',
[
(math.inf, 0.0, 1.0, 0.0, 1.0, math.inf),
(math.nan, 0.0, 1.0, 0.0, 1.0, math.nan),
(1e308, -1e308, 1e308, 0.0, 1.0, math.nan),
(0.0, -1e308, 1e308, 0.0, 1e308, math.nan),
(1e308, 0.0, 1e308, -1e308, 1e308, math.inf),
(1e308, 0.0, 0.5, 0.0, 2.0, math.inf),
],
)
def test_remap_preserves_nonfinite_arithmetic(
value: float,
old_min: float,
old_max: float,
new_min: float,
new_max: float,
expected: float,
) -> None:
"""Leave nonfinite inputs, differences and final overflow unchanged."""
result = converters.remap(value, old_min, old_max, new_min, new_max)
if math.isnan(expected):
assert math.isnan(result)
else:
assert result == expected
31 changes: 31 additions & 0 deletions python_utils/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,14 @@ def remap( # pyright: ignore[reportInconsistentOverload]
>>> remap(46.0, 0.0, 100.0, -80.0, 10.0)
-38.6

Avoid losing a representable float result to an intermediate product
that overflows or rounds to zero:

>>> remap(1e200, 0.0, 1e200, 0.0, 1e200)
1e+200
>>> remap(1e-200, 0.0, 1e-200, 0.0, 1e-200)
1e-200

I added using decimal.Decimal so floating point math errors can be avoided.
Here is an example of a floating point math error
>>> 0.1 + 0.1 + 0.1
Expand Down Expand Up @@ -534,6 +542,29 @@ def remap( # pyright: ignore[reportInconsistentOverload]
# worth it.
new_value = (value - old_min) * new_range # type: ignore[operator] # pyright: ignore[reportOperatorIssue, reportUnknownVariableType]

if type_ is float and (
math.isinf(typing.cast(float, new_value)) or new_value == 0
):
offset = typing.cast(float, value) - typing.cast(float, old_min)
if offset and all(
math.isfinite(part) for part in (offset, old_range, new_range)
):
# Reordering float operations can still round a subnormal result
# twice. Compute this exceptional quotient exactly, then round
# once. Ordinary calculations do not need the fractions import.
from fractions import Fraction

scaled = (
Fraction(offset) * Fraction(new_range) / Fraction(old_range)
)
try:
rounded = float(scaled)
except OverflowError:
# A genuinely overflowing quotient keeps the original result.
pass
else:
return typing.cast(_TN, rounded + typing.cast(float, new_min))

# Integer inputs use floor division to keep the result integral; float and
# Decimal inputs use true division.
if type_ is int:
Expand Down
Loading