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

Rob Cliffe rob.cliffe at btinternet.com
Wed Aug 3 10:36:39 EDT 2016



On 03/08/2016 00:23, Greg Ewing wrote:
> David Mertz wrote:
>> It really doesn't make sense to me that a clamp() function would 
>> *limit to* a NaN.
>
> Keep in mind that the NaNs involved have probably arisen
> from some other computation that went wrong, and that
> the purpose of the whole NaN system is to propagate an
> indication of that wrongness so that it's evident in the
> final result.
>
> So here's how I see it:
>
> clamp(NaN, y, z) is asking "Is an unknown number between
> y and z?" The answer to that is not known, so the result
> should be NaN.
>
> clamp(x, y, NaN) is asking "Is x between y and an unknown
> number?" If x > y, the answer to that is not known, so the
> result should be NaN.
+1 so far
>
> If x < y, you might argue that the result should be y.
> But consider clamp(x, 2, 1). You're asking it to limit
> x to a value not less than 2 and not greater than 1.
> There's no such number, so arguably the result should
> be NaN.
I think clamp(x,2,1) should raise ValueError.  It's asking for something 
impossible.
>
> If you accept that, then clamp(x, y, NaN) should be
> NaN in all cases, since we don't know that the upper
> bound isn't less than the lower bound.
+0.8.  Returning y when x<y might suit some applications better, but 
"resist the temptation to guess".
Rob Cliffe
>
>
> So in summary, I think it should be:
>
> clamp(NaN, y, z) --> NaN
> clamp(x, NaN, z) --> NaN
> clamp(x, y, NaN) --> NaN
> clamp(x, y, z) --> NaN if z < y
>



More information about the Python-ideas mailing list