David Mertz wrote:
> NaN is an IEEE-854 value, everything you
> mention is precisely identical of floats.
> Is your argument that we need to stop using the '<' operator for floats
> also?!
Nope, but I simply ignored in this case IEEE 754-2019 (that supersedes IEEE
854) and I raised an exception, if any number tried to do any comparison with a
(s)NaN. And the same for non-comparable sets.
This is because NaN, IMHO, it's not the right name for the entity. A number
can't be Not a Number. It's an Undefined Number.
Think about 0/0. Suppose that exists an x so 0/0 = x. If so, 0*x = 0. But this
is valid for **every** x. So x is a number, but it's undefined. It can be 1,
100, pi/4, 10.5!, -e. So you can't say if it's greater or smaller or equal to
any other number, NaN included of course!
So you **can't** say 5 < NaN is false. It could be true or false, it's like the
spin of an electron. No, it's worse, since you'll never know if NaN is greater
or lesser than 5, you can't measure it in any way.
But IEEE 754-2019 is written mainly for C and Assembly. And you can't return
nothing in a comparison between two floats. So they take the most practical
solution: return false.
But Python and high level languages have another option: raise an exception.
And this is IMHO the most sane solution, because you **can't** compare NaNs.
Think about a list with a NaN inside. Ok, now the sorting algorithm simply
don't move the NaN.
But what if we change the algorithm and we move also NaNs? Where to put them?
At the begin of the list? At the end?
Even if the list is composed only by NaNs, every position is **wrong**. Because
you can't know if the NaN is greater, equal or lesser than any other number.
So, an exception should be raised. And the same for sets.
This obviously does not apply to total ordering. Even if I think mathematically
has no sense, IEEE 754 clearly defined a total ordering, also for NaNs. So a
total_ordering() key function, passed to sort functions, should order as IEEE
754 declares, without raising exceptions. There's a bug opened somewhere about
this key function.
This is what I've done. Unluckily, the API now works this way. It's not a big
problem anyway. You have only to pass as key to the sort function:
```
def sortNans(x):
try:
if math.isnan(x):
return float("+inf")
except TypeError
pass
return x
```
and do
sorted(iterable_with_nans, key=sortNans)
This key does not distinguish between NaN and -NaN... but who cares! Since NaN
is undefined, it could be also negative, so it's sign is meaningless (except
for total ordering). And the result is wrong... but I repeat, who cares? :D
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/LM22TNILN2INCZVIPXIUEOKHZ5RJKS5Q/
Code of Conduct: http://python.org/psf/codeofconduct/