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

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Aug 2 19:23:06 EDT 2016


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.

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.

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.

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

-- 
Greg


More information about the Python-ideas mailing list