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

Chris Barker chris.barker at noaa.gov
Tue Aug 2 13:02:11 EDT 2016


On Mon, Aug 1, 2016 at 1:10 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> It means that this clamp() function would have to be implemented in C.
> It *doesn't* mean that it will have to convert its arguments to floats,
> or reject non-float arguments.
>

sure -- though I hope it would special-case and be most efficient for
floats.  However, for the most part, the math module IS all about floats --
though I don't suppose there is any harm in allowing other types.

> This follows the IEEE spec -- so the only correct result from
> >
> > clip(x, float('nan')) is NaN.
>
> I don't agree that this is the "only correct result".
>

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.


That's why I said that it was an accident of implementation that passing
> a NAN as one of the lower or upper bounds will be equivalent to setting
> the bounds to minus/plus infinity:


exactly -- and we should not have the results be an accident of
implimentation -- but rather be thougth out, and follow IEE754 intent.

I suppose we could rule that case out: if either bound is a NAN, raise
> an exception. But that will require a conversion to float, which may
> fail. I'd rather just document that passing NANs as bounds will lead to
> implementation-specific behaviour that you cannot rely on it.


why not say that passing NaNs as bounds will result in NaN result? At least
if the value is a float -- if it's anything else than maybe an exception,
as NaN does not make sense for anything else anyway.


> If you
> want to specify an unbounded limit, pass None or an infinity with the
> right sign.


exactly -- that's there, so why not let NaN be NaN?

-CHB



-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160802/fdeb9361/attachment.html>


More information about the Python-ideas mailing list