[Python-Dev] Why is nan != nan?
Steven D'Aprano
steve at pearwood.info
Fri Mar 26 02:10:54 CET 2010
On Fri, 26 Mar 2010 09:45:51 am Greg Ewing wrote:
> Georg Brandl wrote:
> > Thinking of each value created by float('nan') as
> > a different nan makes sense to my naive mind, and it also explains
> > nicely the behavior present right now.
>
> Not entirely:
>
> x = float('NaN')
> y = x
> if x == y:
> ...
>
> There it's hard to argue that the NaNs being compared
> result from different operations.
But unlike us, the equality operator only has a pinhole view of the
operands. It can't distinguish between your example and this:
x = float('nan')
y = some_complex_calculation(x)
if x == y:
...
where y merely happens to end up with the same object as x by some quirk
of implementation.
> It does suggest a potential compromise, though: a single
> NaN object compares equal to itself, but different NaN
> objects are never equal (more or less what dict membership
> testing does now, but extended to all == comparisons).
>
> Whether that's a *sane* compromise I'm not sure.
What do we do with Decimal? Aren't we committed to matching the Decimal
standard, in which case aren't we committed to this?
x = Decimal('nan')
assert x != x
If that's the case, then float NANs and Decimal NANs will behave
differently. I think that's a mistake.
For what it's worth, I'm -1 on allowing NANs to test equal to any NAN,
including itself. However, I would be -0 on the following compromise:
Allow NANs to test equal to themselves (identity testing).
math module to grow a function ieee_equals(x, y) that keeps the current
behaviour.
--
Steven D'Aprano
More information about the Python-Dev
mailing list