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

Steven D'Aprano steve at pearwood.info
Thu Aug 4 08:42:55 EDT 2016


On Wed, Aug 03, 2016 at 11:04:33AM +1200, Greg Ewing wrote:
> Steven D'Aprano wrote:
> >In any case, clamping is based of < and > comparisons, which are 
> >well-specified by IEEE 754 even when NANs are included:
> 
> Those rules are not enough to determine the behaviour of
> functions such as min, max and clamp, though.

IEEE-754 specifies the behaviour of min() and max() with a NAN argument. 
See my previous email.


> >>why not say that passing NaNs as bounds will result in NaN result?
> >
> >Because that means that EVERY call to clamp() has to convert both bounds 
> >to float and see if they are NANs.
> 
> No, it doesn't -- it only needs to check whether they are
> NaN if they're *already* floats. If they're not floats,
> they're obviously not NaN, so just leave them alone.

That's wrong. Decimal has NANs. Other numeric types could potentially 
have NANs too.


> (Actually, that's not quite true, since they could be a
> custom type with its own notion of NaN-ness -- maybe we
> could do with an __isnan__ protocol?)

I would like to see a common "isnan" function or method for both floats 
and Decimal, because I'm sick of writing code like:

try:
    flag = x.is_nan()  # Decimal?
except AttributeError:
    flag = math.isnan(x)  # float


Note that the spelling is different too, for extra sadness :-(



-- 
Steve


More information about the Python-ideas mailing list