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

Steven D'Aprano steve at pearwood.info
Thu Aug 4 21:54:34 EDT 2016


On Wed, Aug 03, 2016 at 08:52:24AM -0700, Chris Barker - NOAA Federal wrote:

> One could argue that:
> 
> clamp(NaN, x,x)
> 
> Is clearly defined as x. But that would require special casing

Not so special:

if lower == upper != None:
    return lower

That's in the spirit of Professor Kahan's admonition that NANs should 
not be treated as a one way street: most calculations that lead to NANs 
will, of course, stay as NANs, but there are cases where a calculation 
on a NAN will lead to a non-NAN:

py> math.hypot(INF, NAN)
inf
py> math.hypot(NAN, INF)
inf
py> NAN**0.0
1.0

If the bounds are equal, then clamp(NAN, a, a) should return a.


> and, "equality" is a bit of an ephemeral concept with floats, so 
> better to return NaN.

Not really. Please read what Kahan says about NANs. He was one of the 
committee members that worked out most of these issues in the nineties. 
He says:

    NaN must not be confused with “Undefined.” On the contrary,  
    IEEE 754 defines NaN perfectly well even though most language
    standards ignore and many compilers deviate from that definition.
    The deviations usually afflict relational expressions, discussed
    below. Arithmetic operations upon NaNs other than SNaNs (see 
    below) never signal INVALID, and always produce NaN unless 
    replacing every NaN operand by any finite or infinite real values
    would produce the same finite or infinite floating-point result 
    independent of the replacements.

That's exactly the situation here: clamp(x, a, a) should return a for 
any finite or infinite x, which means it should do the same when x is a 
NAN as well.

https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF

See page 7.



-- 
Steve


More information about the Python-ideas mailing list