
On 2021-08-30 04:31, Steven D'Aprano wrote:
On Sun, Aug 29, 2021 at 08:20:07PM -0400, tritium-list@sdamon.com wrote:
Not to go off on too much of a tangent, but isn't NaN unorderable? Its greater than nothing, and less than nothing, so you can't even really sort a list with a NaN value in it (..though I'm sure python does sort it by some metric for practical reasons) - it would be impossible to find a NaN with a binary search... it would be impossible to have a NaN in an ordered sequence .... wouldn't it?
Sorting NANs will end up arranging them in arbitrary positions, and spoil the order of other values:
>>> from math import nan >>> sorted([4, nan, 2, 5, 1, nan, 3, 0]) [4, nan, 0, 1, 2, 5, nan, 3]
I *think* Timsort will end up leaving each NAN in its original position, but other implementations may do something different. However you sort, they end up messing the order up.
However we could add a function, totalorder, which can be used as a key function to force an order on NANs. The 2008 version of the IEEE-754 standard recommends such a function:
from some_module import totalorder sorted([4, nan, 2, 5, 1, nan, 3, 0], key=totalorder) # --> [nan, nan, 0, 1, 2, 3, 4, 5]
It would be nice if such a totalorder function worked correctly on both floats and Decimals. Anyone feel up to writing one?
How about: def totalorder(x): return (0,) if math.isnan(x) else (1, x)
Decimal already has a `compare_total` method, but I'm unsure if it behaves the expected way. But we have no equivalent key function for floats.