[Python-ideas] Consider adding clip or clamp function to math

Alexander Belopolsky alexander.belopolsky at gmail.com
Tue Aug 2 13:19:03 EDT 2016


On Tue, Aug 2, 2016 at 1:02 PM, Chris Barker <chris.barker at noaa.gov> wrote:
> I don't think IEE754 says anything about a "clip" function, but a NaN is
> neither greater than, less than, nor equal to any value -- so when  you ask
> if, for example, for the input value if it is less than or equal to NaN, but
> NaN if NaN is great then the input, there is no answer -- the spirit of IEEE
> NaN handling leads to NaN being the only correct result.
>
> Note that I'm pretty sure that min() and max() are wrong here, too.

Builtin max is wrong

>>> nan = float('nan')
>>> max(nan, 1)
nan
>>> max(1, nan)
1

but numpy's maximum gets it right:

>>> numpy.maximum(nan, 1)
nan
>>> numpy.maximum(1, nan)
nan

And here is how numpy defines clip:

>>> numpy.clip(nan, 1, 2)
nan
>>> numpy.clip(1, 1, nan)
1.0
>>> numpy.clip(1, nan, nan)
1.0

I am not sure I like the last two results.


More information about the Python-ideas mailing list