Re: table sort: IEEE floating-point number NaN?
Francisco Olarte <[email protected]> Sun, 26 Apr 2026 09:46:50 +0200
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CA+bJJby1pq6ydOUo-=OyOc+fgyWiD9narJrBF2LmSGwo+DhDiA@mail.gmail.com> |
On Sun, 26 Apr 2026 at 00:49, 'Lars Müller' via lua-l < [email protected]> wrote: > If passing NaNs may cause a sorting algorithm to produce an error, that's > a feature. You must not try to sort the unsortable (and if you do, you > should be explicit about how you want it sorted). -Lars > <kidding for="political correctness"> If you can sort by being explicit then it is nor unsortable, just "hard to sort". </kidding> The sorter goes through a comparator, it is easy to define one which sorts nan in a defined place, like some SQL engines do with nulls and NULLS FIRST/LAST clauses: -- Sort NANs first, even before -Inf. function nan_first_less(a,b) if is_nan(b) then return false -- NaN is not less than nothing, even other NaN elseif is_nan(a) then return true -- B is not a Nan, so a is less then it. else return a<b -- no NaNs, so this works right. end end is_nan is trivial and has been done here before. This can be used to sort NAN first or last. It can be optimized a bit by unrolling is_nan. Also, knowing floating point numbers are enumerable, you can place NaN anywhere in the FP range, but it is a bit harder, I do not recall if Lua sports signeds zeros, but with a proper comparator you can also do things like -0,NaN,+0, or signaling before non signaling nans. IEE754 numbers are just a data chunk for a sorter, 64 bits in RAM, with a proper comparator they can always be sorted in any way you want, you just have to be a little careful writing it, as soon as you enter Nan (there are many representations for them, although I think lua just generates one)/Inf/unnormalized/signed zero territory things get a bit bug prone. Francisco Olarte. -- You received this message because you are subscribed to the Google Groups "lua-l" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/lua-l/CA%2BbJJby1pq6ydOUo-%3DOyOc%2BfgyWiD9narJrBF2LmSGwo%2BDhDiA%40mail.gmail.com.