Keep template remap clamp output within the output range (#187660)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-20 22:57:32 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5577d8150a
commit 232f99892c
2 changed files with 22 additions and 1 deletions
@@ -502,4 +502,9 @@ class MathExtension(BaseTemplateExtension):
if steps:
normalized = round(normalized * steps) / steps
return out_min_num + (normalized * (out_max_num - out_min_num))
result = out_min_num + (normalized * (out_max_num - out_min_num))
if edges == "clamp":
# Rounding in the linear map can overshoot the output bounds.
low, high = sorted((out_min_num, out_max_num))
return max(low, min(high, result))
return result
@@ -511,6 +511,22 @@ def test_remap(hass: HomeAssistant) -> None:
render(hass, case)
@pytest.mark.parametrize(
("value", "out_min", "out_max", "expected"),
[
pytest.param(5, 0.3, 0.9, 0.9, id="above_range"),
pytest.param(5, 0.7, 0.1, 0.1, id="above_range_inverted_output"),
pytest.param(5, 72.0, -75.8, -75.8, id="above_range_mixed_sign_output"),
pytest.param(-5, 0.3, 0.9, 0.3, id="below_range"),
],
)
def test_remap_clamp_stays_within_output_range(
value: float, out_min: float, out_max: float, expected: float
) -> None:
"""Test clamp never returns a value outside the output range."""
assert MathExtension.remap(value, 0, 1, out_min, out_max, edges="clamp") == expected
def test_remap_with_steps(hass: HomeAssistant) -> None:
"""Test remap function with steps parameter."""
# Test basic stepping - quantize to 10 steps