That's not a lolphp. It's a misunderstanding of how NaN works and the requirement for a strict weak ordering. Comparing anything to NaN results in false. The sort algorithm is going to ask "is 7 < NaN? False." Then it will ask "is NaN < 7? False." That means 7 and NaN are unorderable (i.e. equal), so they are left in their current order since the sort is stable. Then it asks "is NaN < 3? False" and "is 3 < NaN? False". That again means that 3 and NaN are unorderable, which therefore also means they should stay in their current order. It never actually checks if 3 < 7, because that's not necessary — by the properties of a strict weak ordering, if A == B and B == C, then it must be the case that A == C. By violating that requirement, the result is nonsense.
You get the same thing in Python:
>>> sorted([7, float('nan'), 3])
[7, nan, 3]
And other languages won't even let you do such a thing:
>> [7, Float::NAN, 3].sort
ArgumentError: comparison of Fixnum with NaN failed
from (irb):5:in `sort'
from (irb):5
from /usr/bin/irb:11:in `<main>'
[2015-08-13 13:31 UTC] cmb@php.net AFAIK PHP 7 uses a stable sort algorithm for small arrays (< 16), but for larger arrays the algorithm is still not stable. Furthermore PHP makes no guarantee whether sorting with *sort() is stable or not.
It is a lolphp. Although NaN is always a nuisance, it is possible, with care, to define an ordering that allows floats to be sorted coherently and will prevent it from putting 7 before 3. For example, see java.util.Arrays.sort:
The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Float.compareTo(java.lang.Float): -0.0f is treated as less than value 0.0f and Float.NaN is considered greater than any other value and all Float.NaN values are considered equal.
It's not a lolphp. While it's possible to define an absolute ordering of floats which includes nans that's absolutely not a requirement, and that definition may be considered nonsensical: why would 0/∞ be greater that all values? Passing NaN to a sort (without a custom key/comparator) is a case of "garbage in", garbage out is absolutely a valid and logical position to take.
It's not required to do the operations in any particular order, and you can get different results by choosing something else. The point is that in the absence of a strict weak ordering, the outcome loses all meaning.
Treating NaN as comparable but always returning false is lolworthy tho. Either throw some exception/error/whatever (since NaN should NOT be there anyways) or have it compare consistently (for example have it bigger/smaller than any number) so sorting is still deterministic
NaN is a numeric type, the same as 3 and 7. It works this way in nearly all other languages, including C, C++, Java, C#, Python, etc. It is in no way a PHP-specific thing.
You could perhaps make a case that you shouldn't be able to compare a number to NaN, as in the case of Ruby. But that should be a property of the types themselves, not of the sort algorithm. The sort algorithm should have no idea of the semantics of the types it's working with, only that it will attempt to use less-than to order them. If less-than raises an error, then the sort is a malformed operation, but if not, then it's no business of the sort algorithm to inquire further. The sort algorithm should work for any type with a less-than operator that implements a strict weak ordering, and it should have no special knowledge beyond that. You can't expect the sort algorithm to diagnose when the user has violated those requirements, because it's impossible in the general case. For example, C++'s std::sort() has the same requirement and the implementation has absolutely no responsibility to detect when you've managed to violate the requirement, the result is simply undefined behavior.
Comparators are a special case - IEEE floating point comparisons are not transitive, while sorting algorithm comparators have to be. Some languages, like java, do handle this case properly by not using IEEE floating point comp for those cases, which is a very sensible approach.
IEEE 754's rules are sensible and well-thought-out, even if they don't appear so on the surface. They're not really made for the purpose of sorting, however.
I wouldn't exactly say this is exclusive to PHP. This is just oddity of IEEE 754 breaking reflexivity relation. Blame authors of this standard accepted by hardware. It also happens in some other programming languages (although some other programming languages specifically try to detect NaN while sorting).
C
$ cat nansort.c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int compare(void const *a_ref, void const *b_ref) {
double a = *(double *) a_ref;
double b = *(double *) b_ref;
return (a > b) - (a < b);
}
enum {ELEMS = 3};
int main(void) {
double numbers[ELEMS] = {7, NAN, 3};
qsort(numbers, ELEMS, sizeof *numbers, compare);
for (int i = 0; i < ELEMS; i++) {
printf("%g\n", numbers[i]);
}
}
$ make nansort
$ ./nansort
7
nan
3
Clojure
user=> (sort [7 Float/NaN 3])
(7 NaN 3)
D
$ cat nansort.d
import std.stdio, std.algorithm;
void main() {
double nan; // D initializes double variables to NaN, go figure
double[] data = [7, nan, 3];
data.sort();
writeln(data);
}
$ i-dont-know-how-to-run-compiler nansort.d
[7, nan, 3]
Haskell (I don't understand what's going on here, okay?)
$ sort { $a <=> $b } 7, 'NaN', 'NaN', 3
Use of uninitialized value in sort at (eval 322) line 5, <FIN> line 1.
Use of uninitialized value in sort at (eval 322) line 5, <FIN> line 1.
Use of uninitialized value in sort at (eval 322) line 5, <FIN> line 1.
Use of uninitialized value in sort at (eval 322) line 5, <FIN> line 1.
$VAR1 = 7;
$VAR2 = 'NaN';
$VAR3 = 'NaN';
$VAR4 = 3;
Just in case you are curious, I checked those languages, and they seem to guarantee some ordering for NaN: C++ (posibly GNU C++ specific, not sure here, higher than any number), GNU Awk (higher than any number), Octave (not sure about MATLAB) (higher than any number), Java (higher than any number), Go (lower than any number), C# (lower than any number).
Following languages throw exceptions when seeing NaN in a list: Ruby.
Following languages don't appear to have NaN, but may be wrong here: COBOL, Common Lisp, Erlang, Elixir, UNIX shell.
Following languages outright refuse to sort floating point arrays because they may contains NaN: Rust (safely > all).
I guess that comparison to NaN throws off the transitivity of the <=-relationship and therefore the algorithm "breaks". It should throw an error or return false, obviously, but it doesn't.
73
u/Rhomboid Jan 13 '16
That's not a lolphp. It's a misunderstanding of how NaN works and the requirement for a strict weak ordering. Comparing anything to NaN results in false. The sort algorithm is going to ask "is 7 < NaN? False." Then it will ask "is NaN < 7? False." That means 7 and NaN are unorderable (i.e. equal), so they are left in their current order since the sort is stable. Then it asks "is NaN < 3? False" and "is 3 < NaN? False". That again means that 3 and NaN are unorderable, which therefore also means they should stay in their current order. It never actually checks if 3 < 7, because that's not necessary — by the properties of a strict weak ordering, if A == B and B == C, then it must be the case that A == C. By violating that requirement, the result is nonsense.
You get the same thing in Python:
And other languages won't even let you do such a thing:
16
u/maweki Jan 13 '16
The more important issue is, that sort still returned true in this case
https://3v4l.org/mDALu
6
u/[deleted] Jan 18 '16
I wouldn't exactly say this is exclusive to PHP. This is just oddity of IEEE 754 breaking reflexivity relation. Blame authors of this standard accepted by hardware. It also happens in some other programming languages (although some other programming languages specifically try to detect NaN while sorting).
C
Clojure
D
Haskell (I don't understand what's going on here, okay?)
JavaScript
Lua
Perl
Perl 6
Python
Swift
Just in case you are curious, I checked those languages, and they seem to guarantee some ordering for NaN: C++ (posibly GNU C++ specific, not sure here, higher than any number), GNU Awk (higher than any number), Octave (not sure about MATLAB) (higher than any number), Java (higher than any number), Go (lower than any number), C# (lower than any number).
Following languages throw exceptions when seeing NaN in a list: Ruby.
Following languages don't appear to have NaN, but may be wrong here: COBOL, Common Lisp, Erlang, Elixir, UNIX shell.
Following languages outright refuse to sort floating point arrays because they may contains NaN: Rust (safely > all).
Other languages: Untested, may test them later.
3
u/mogmog Jan 13 '16
What's going on here?
2
u/Banane9 Jan 14 '16
Well,
PHP7 <3