[Python-ideas] Consider adding clip or clamp function to math
steve at pearwood.info
Sun Jul 31 04:19:39 EDT 2016
On Sat, Jul 30, 2016 at 09:41:07PM -0700, David Mertz wrote:
> Is there some special subtlety or edge case where a hand rolled function
> will go wrong?
Depends on the person doing the hand rolling :-)
I'm not sure how your version would work with NANs, and I haven't
bothered to try it to find out, but I like this version:
def clamp(value, lower=None, upper=None):
"""Clamp value to the closed interval lower...upper.
The limits lower and upper can be set to None to mean -∞ and +∞
if not (lower is None or upper is None):
if lower > upper:
raise ValueError('lower must be <= upper')
if lower is not None and value < lower:
value = lower
elif upper is not None and value > upper:
value = upper
which does support NANs for the value being clamped. (It returns the NAN
unchanged.) It also avoids the expense of function calls to min and max,
and will check that the lower and upper bounds are in the right order
even if you run with assertions turned off.
I don't think I've missed any cases.
More information about the Python-ideas