Re: [Python-ideas] Consider adding clip or clamp function to math
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
On Thu, Aug 4, 2016 at 10:42 PM, Steven D'Aprano <steve@pearwood.info> wrote:
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 :-(
def isnan(x): return x != x Might land you a few false positives, but not many. And it's IEEE compliant. ChrisA
On Thu, Aug 04, 2016 at 11:12:36PM +1000, Chris Angelico wrote:
On Thu, Aug 4, 2016 at 10:42 PM, Steven D'Aprano <steve@pearwood.info> wrote:
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 :-(
def isnan(x): return x != x
Might land you a few false positives, but not many. And it's IEEE compliant.
That's what I used to use before math.isnan existed. But I fear some clever clogs deciding that they like NANs but don't like that NANs violate reflexivity, or merely optimizing equality like this: def __eq__(self, other): # optimisation if self is other: return True # more expensive comparison ... In the absence of an isnan() method or function, falling back on x!=x is okay as a last resort, but I wouldn't want to rely on it as the first resort. -- Steve
participants (2)
-
Chris Angelico
-
Steven D'Aprano