Clamp a numeric input to a chosen interval

Clamp a numeric input to a chosen interval

A clamp maps every value into an inclusive interval: values below the lower bound become that bound, values above the upper bound become the upper bound, and values already inside remain unchanged. This is useful when a configuration or form has already been parsed as a number but a downstream calculation accepts only a limited range.

max(lower, min(value, upper)) expresses that rule directly. The inner min caps the value at upper; the outer max then raises any remaining too-small result to lower. In this example, a requested opacity of 1.4 becomes 1.0, while 0.35 is preserved. The assertions cover all three outcomes, including the lower-bound case.

The bounds must be ordered. The helper raises ValueError instead of silently returning a surprising value when lower exceeds upper. It also assumes inputs are mutually comparable numeric values; it does not parse strings, reject NaN, or establish application-specific units. If floats can be non-finite, validate them before clamping.

min() and max() are built-in functions available in all supported Python versions. Their normal comparison behavior is documented in the Python built-in functions reference.

AI assistance disclosure: This article was drafted with AI assistance and should be adapted to the receiving application's validation rules.


def clamp(value, lower, upper):
    if lower > upper:
        raise ValueError("lower bound must not exceed upper bound")
    return max(lower, min(value, upper))


assert clamp(-0.2, 0.0, 1.0) == 0.0
assert clamp(0.35, 0.0, 1.0) == 0.35
assert clamp(1.4, 0.0, 1.0) == 1.0

print(f"opacity={clamp(1.4, 0.0, 1.0):.1f}")
opacity=1.0

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic