two case studies of NaN
The post highlights two instances where NaN's non-reflexive equality (NaN != NaN) breaks implicit assumptions in language design. In Python, list equality uses an optimization: elements are compared by identity first, and only if identities differ are they compared by value. This causes `[nan] == [nan]` to return True, even though `nan == nan` is False. The Python reference manual states that equality should be reflexive, but NaN violates this. The post notes this is not necessarily wrong but points out the inconsistency. In Lua, numerical for-loops (e.g., `for i = 1, 10 do ... end`) behave unexpectedly with NaN. The reference implementation (PUC-Rio Lua) executes loops with NaN as initial value once, because the first check uses `limit < init` (which is false for NaN), but subsequent iterations check `idx <= limit` (which fails). When NaN is used as the step, it is always treated as negative because the check `0 < step` is false for NaN. This leads to loops executing once or never, depending on the parameters. The behavior is undocumented and likely an oversight; Lua already errors on zero step but not on NaN.
NaN's non-reflexive equality can cause subtle bugs in language features that assume reflexivity.