[Python-ideas] math.inf and math.nan constants
rosuav at gmail.com
Fri Jan 9 13:12:26 CET 2015
On Fri, Jan 9, 2015 at 10:58 PM, Alexander Heger <python at 2sn.net> wrote:
> here another odd issue related to NaN arithmetics:
>>>> nan = float('nan')
>>>> nan is nan
>>>> nan == nan
> this is what we want. Good. But
>>>> x = (nan,)
>>>> x is x
>>>> x == x
> ... hmm ... apparently the comparison uses ID before using == ? for
> tuple elements?
It doesn't even compare them. Consider:
>>> class Different:
... def __eq__(self, other):
... return False
>>> x = Different()
>>> x == x
Comparing 139945362930712 with 139945362930712
>>> tup = x,
>>> tup == tup
A tuple is equal to itself, for efficiency's sake, and doesn't go in
and check that all its elements are equal to themselves.
> on the other hand
>>>> (nan,) is (nan,)
>>>> (nan,) == (nan,)
This, however, shows your point better. Likewise, using my Different
class shows that the comparison isn't made:
>>> (x,) is (x,)
>>> (x,) == (x,)
> I guess we see from
>>>> float('nan') is float('nan')
>>>> (float('nan'),) == (float('nan'),)
Right; they're different objects, so the short-cut isn't taken.
It's a shortcut that works safely for every sane object except NaN.
You won't find many non-buggy objects that aren't equal to themselves.
> I understand why they all give the results they do, however, I think
> the second comparison in (2) should give False and, more importantly,
> the first comparison of (4) should be True - maths.nan should be a
> singleton - even if we allow to float.make_nan() to produce NaNs with
> different payloads - but maths.nan could be just one thing, one
> instance, the numerical counterpart to None.
Why should math.nan be a singleton? Consider:
>>> float("1.0") is float("1.0")
>>> (float("1.0"),) == (float("1.0"),)
Even with integers, although CPython caches some small ones:
>>> int("12345") is int("12345")
>>> (int("12345"),) == (int("12345"),)
(And CPython also caches literals, so both these tests have to use
explicit constructor calls.)
I think we can all agree that the number 12345 is unique - there
aren't two such numbers. So if we're allowed to have two int objects
representing the exact same number, why should NaN (which represents
the vastly infinite space of non-numbers) be unique?
More information about the Python-ideas