The point of this answer is to explain why the language design choice of having Math.min
be fully commutative makes sense.
I am curious to know why -0 < 0 happens?
It doesn't really; <
is a separate operation from "minimum", and Math.min
isn't based solely on IEEE <
comparison like b<a ? b : a
.
That would be non-commutative wrt. NaN as well as signed-zero. (<
is false if either operand is NaN, so that would produce a
).
As far as principle of least surprise, it would be at least as surprising (if not moreso) if Math.min(-1,NaN)
was NaN
but Math.min(NaN, -1)
was -1
.
The JS language designers wanted Math.min
to be NaN-propagating, so basing it just on <
wasn't possible anyway. They chose to make it fully commutative including for signed zero, which seems like a sensible decision.
OTOH, most code doesn't care about signed zero, so this language design choice costs a bit of performance for everyone to cater to the rare cases where someone wants well-defined signed-zero semantics.
If you want a simple operation that ignores NaN in an array, iterate yourself with current_min = x < current_min ? x : current_min
. That will ignore all NaN, and also ignore -0
for current_min <= +0.0
(IEEE comparison). Or if current_min
starts out NaN, it will stay NaN. Many of those things are undesirable for a Math.min
function, so it doesn't work that way.
If you compare other languages, the C standard fmin
function is commutative wrt. NaN (returning the non-NaN if there is one, opposite of JS), but is not required to be commutative wrt. signed zero. Some C implementations choose to work like JS for +-0.0 for fmin
/ fmax
.
But C++ std::min
is defined purely in terms of a <
operation, so it does work that way. (It's intended to work generically, including on non-numeric types like strings; unlike std::fmin
it doesn't have any FP-specific rules.) See What is the instruction that gives branchless FP min and max on x86? re: x86's minps
instruction and C++ std::min
which are both non-commutative wrt. NaN and signed zero.
IEEE 754 <
doesn't give you a total order over distinct FP numbers. Math.min
does except for NaNs (e.g. if you built a sorting network with it and Math.max
.) Its order disagrees with Math.max
: they both return NaN if there is one, so a sorting network using min/max comparators would produce all NaNs if there were any in the input array.
Math.min
alone wouldn't be sufficient for sorting without something like ==
to see which arg it returned, but that breaks down for signed zero as well as NaN.