I like floats. On modern CPUs, invalid floating-point calculations normally don’t trigger hardware exceptions. Instead, if the result can’t be represented by the data type, the operation will return a special value of ± Infinity or NaN.
Because NaN represents multiple arithmetically-incompatible solutions to underlying equations, this special value is never equal to itself:
In contrast, because Infinity represents multiple arithmetically-incompatible solutions to underlying equations, this special value is always equal to itself:
Because it’s not a number, NaN taints the result of any arithmetic operation in which it shows up as an operand:
The above is always true, except when it isn’t:
In C, Boolean expressions are numbers. Because NaN is not a number, it is always true:
JavaScript inherits the syntax of Boolean expressions from C. Because of this, in JavaScript, NaN is always false (demo):
Since NaN is never equal to anything else, it follows that ~NaN is equal ~Infinity:
In other floating-point news, JavaScript numbers are floats, so some terminating loops don’t terminate:
But enough with floats! In JavaScript, arrays are objects under the hood and can be used as sparse hash tables. On an unrelated note, in JavaScript, numbers are floats:
Of course, NaN is a valid index and, in this instance, is always equal to itself:
In C, because NaN is not a number, it can be positive or negative. This is a common way to detect knock-off CPUs (demo #1, #2):
Thank you and come back again for more episodes of computing.
For more programming tips, you might also enjoy my article on page 42 of Paged Out #009.