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

Chris Barker chris.barker at noaa.gov
Tue Aug 2 16:50:37 EDT 2016


On Tue, Aug 2, 2016 at 11:45 AM, Random832 <random832 at fastmail.com> wrote:

> Sure, but what the standard doesn't say is exactly what sequence of
> comparisons is entailed by a clamp function.
>
> def clamp(x, a, b):
>     if x < a: return a
>     else:
>         if x > b: return b
>         else: return x
>
> def clamp(x, a, b):
>     if a <= x:
>         if x <= b: return x
>         else: return b
>     else: return a
>
> There are, technically, eight possible naive implementations, varying
> along three axes:
>

Exactly-- I thought this was self evident, but apparently not -- thanks for
spelling it out.


> All such functions are equivalent if {a, b, x} is a set over which the
> relational operators define a total ordering, and a <= b. However, this
> is not the case if NaN is used for any of the arguments.
>

Exactly again -- NaN's are kind of a pain :-(

As for the convert to floats issue -- correctness is more important than
performance, and performance is probably most important for the special
case of all floats. (or floats and integers, I suppose) -- i'm sure we can
find a solution. LIkely something iike the second option above would work
fine, and also work for anything with an ordinary total ordering.

-Chris


-- 

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/5ce0d5e8/attachment.html>


More information about the Python-ideas mailing list