Search code examples
javascriptfloating-pointieee-754

Does `always returns unordered result` meaning `returns false`


I'm reading about NaN here and it says that:

A comparison with a NaN always returns an unordered result even when comparing with itself.

I'm confused about the word unordered. For practical reasons, does it mean that comparison will always evaluate to false? It seems to be the case:

// all statemens below evaluate to false

NaN === NaN
NaN > NaN
NaN < NaN

NaN > 3
NaN < 3
NaN === 3

Solution

  • Yes. When comparing two floating point numbers a and b, there will be exactly 1 of 4 outcomes:

    • a is less than b
    • a is equal to b
    • a is greater than b
    • a and b are unordered.

    The IEEE754 spec states that a and b are unordered when either a or b is a NaN (which includes the case when both a and b are NaN).

    In most languages the first 3 have their own predicates (typically <, ==, >). The unordered case does not, but can be tested by checking that all the others are false.