December 9, 2025
When zero beefs with minus zero
Using Floating Point Numbers as Hash Keys (2017)
Floats as keys? Devs feud over NaN and the cursed minus zero
TLDR: A deep dive warns that using decimal numbers as table keys can be risky unless equality is crystal clear. Commenters spar over rules: JavaScript’s SameValueZero and Java’s NaN handling vs the missing C++ take, underscoring that consistent comparison makes or breaks your data lookups.
Floats—those decimal-y numbers computers juggle—just crashed the dinner party as hash table keys, and the comment section turned into a popcorn-worthy show. The article says most folks avoid using floats as keys because tiny rounding errors can make “equal” numbers disagree. Cue strong feelings: some readers declare “never do this,” while others argue it’s fine if you compare them exactly and don’t play the “almost equal” game. Special guests at this circus: NaN (Not a Number), infinity, and the internet’s favorite weirdo, minus zero.
The drama peaked when anematode rolled in with JavaScript’s “SameValueZero” rule—basically, the language’s official way to decide when numbers are “the same,” with NaN equal to NaN and -0 treated like 0. Java vets like Terr_ reminisced: Java’s Float hashing collapses all those “not-a-number” values into one tidy bucket, which sparked cheers from the “make it consistent” crowd. Meanwhile, advael was bummed the article never covered C++, prompting a chorus of “guess we’ll DIY.” The meme energy was strong: minus zero got roasted as the edgy twin, and NaN was dubbed the friend who never agrees with anyone—until JavaScript says it must. Verdict? The community is split between caution and cleverness, but everyone agrees the rules matter more than the math vibes.
Key Points
- •Floating point numbers can be used as hash keys if suitable comparison and hash functions are defined.
- •Rounding and truncation errors can affect hash keys, making float-based indexing error-prone in many situations.
- •Approximate equality (e.g., epsilon comparison) is incompatible with hashing because it collapses many values to the same hash.
- •Floats themselves are precise values; equality comparisons are safe where no rounding has occurred, and some arithmetic identities hold exactly.
- •Languages differ in handling float keys and special values (NaN, minus zero, infinity); in some (JavaScript, older Lua) floats are the only numeric type.