On 10 October 2012 02:14, Steven D'Aprano <firstname.lastname@example.org> wrote:
On 10/10/12 09:13, Joshua Landau wrote:Because that would complicate Python's using floats for absolutely no benefit.
Just a curiosity here (as I can guess of plausible reasons myself, so there
probably are some official stances).
Is there a reason NaNs are not instances of NaN class?
Instead of float operations always returning a float, they would have to return
a float or a NAN. To check for a valid floating point instance, instead of
you would have to say:
isinstance(x, (float, NAN))
>>> class NAN(float):
... def __new__(self):
... return float.__new__(self, "nan")
... def __eq__(self, other):
... return other is self
>>> isinstance(NAN(), float)
>>> NAN() is NAN()
>>> NAN() == NAN()
>>> x = NAN()
>>> x is x
>>> x == x
And what about infinities, denorm numbers, and negative zero? Do they get
dedicated classes too?
And what is the point of this added complexity? Nothing.
You *still* have the rule that "x == x for all x, except for NANs".
The only difference is that "NANs" now means "instances of NAN class" rather than
"NAN floats" (and Decimals).
Working with IEEE 754 floats is now far more of
a nuisance because some valid floating point values aren't floats but have a
different class, but nothing meaningful is different.
Making NANs their own class wouldn't give you that. If we wanted thatThen x == x would be True (as they want), but [this NaN] == [that NaN]
would be False, as expected.
behaviour, we could have it without introducing a NAN class: just change the
list __eq__ method to scan the list for a NAN using math.isnan before checking
whether the lists were identical.
>>> x == x
>>> [NAN()] == [NAN()]
But that would defeat the purpose of the identity check (an optimization to
avoid scanning the list)! Replacing math.isnan with isinstance doesn't change
that.That question has already been raised, and answered, repeatedly in this thread.
I guess that raises the question about why x == x but sqrt(-1) != sqrt(-1),
Container equalities are not a big deal. I'm not sure what problem you thinkbut it seems a lot less of a big deal than all of the exceptions with
you are solving.