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

Chris Barker chris.barker at noaa.gov
Thu Aug 4 14:01:38 EDT 2016


On Thu, Aug 4, 2016 at 5:35 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> The IEEE 754 standard tells us what min(x, NAN) and max(x, NAN) should
> be: in both cases it is x.
>
> https://en.wikipedia.org/wiki/IEEE_754_revision#min_and_max


I thought an earlier post said something about a alternatvie min and max?
-- but anyway, consisetncy with min and max is a pretty good argument.

Quote:
>
>     For instance max{x, y} should deliver the same result as max{y, x} but
>     almost no implementations do that when x is NaN. There are good
>     reasons to define max{NaN, 5} := max{5, NaN} := 5 though many would
>     disagree.
>

I don't disagree that there are good reason, just that it's the final way
to go :-) -- but if Kahan equivocates, then there isn't one way to go :-)

As you propose it, clamp() is no use to me: it unnecessarily converts the
> bounds to float, which may raise an exception.


no it doesn't -- that's only one way to implement it. We really should
decide on the behaviour we want, and then figure out how to implemt it --
not choose something because it's easier to implement.

there was an earlier post with an implementation that would give the
NaN-poising behaviour, but would also work with any total-ordered type as
well. not that's thought about possible edge cases.


I think this is it:

def clamp(x, a, b):
    if a <= x:
        if x <= b: return x
        else: return b
    else: return a

hmm -- doesn't work for x is NaN, but limits are not -- but I'm sure that
could be worked out.

In [*32*]: clamp(nan, 0, 100)

Out[*32*]: 0

-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/20160804/964559d1/attachment.html>


More information about the Python-ideas mailing list