HeadlinesBriefing favicon HeadlinesBriefing.com

NaN Behavior in Python and Lua

Hacker News •
×

IEEE-754 NaN is weird and often left unaccounted for in programming language design. Two case studies illustrate how implicit assumptions break with NaN.

Case study 1: Python — List equality uses an identity optimization: elements are first compared by identity, then equality if identities differ. This assumes reflexivity (x is y implies x == y), documented in the Python 3 reference manual. But NaN != NaN, so `[nan] == [nan]` returns True because the identity check passes. This isn't necessarily wrong, but the optimization leaves NaN with weird behavior.

Case study 2: Lua — Numerical for-loops with NaN (0/0) produce unintuitive results in the reference implementation (PUC-Rio Lua). Loops like `for i = 0/0, 10 do end` execute once because the initial check uses `limit < init`, but subsequent iterations check `idx <= limit`. When NaN is the step, it's always treated as negative since `0 < step` is false for NaN. This behavior is undocumented, likely an oversight. The fix would be to disallow NaN in for-loops, as Lua already does for zero step.

Chris Siebenmann previously documented NaN weirdness as map keys in Go, making three case studies. NaN's oddity propagates unexpected behavior across languages.