hn.today

If It Floats

blog.coredump.cx47 points3 comments
Screenshot of If It Floats

A playful tour of floating-point quirks argues that IEEE 754 is less elegant than surprising. On many modern CPUs, invalid calculations produce Infinity or NaN rather than raising exceptions. Infinity compares equal to itself, while NaN does not; NaN generally propagates through calculations, though an operation such as raising it to the zero power can produce 1. The examples then contrast languages: C treats NaN as true in a Boolean condition, while JavaScript treats it as false. JavaScript’s bitwise conversion also makes expressions involving NaN and Infinity unexpectedly compare equal.

The piece moves from these rules to practical oddities. In JavaScript, numbers are floating-point values, so repeatedly adding 1 to a number around 10^16 may not change it, leaving a loop stuck. NaN can also be used as an object key: property access converts it to the string “NaN,” so looking up the same key through a NaN calculation retrieves the stored value. Finally, a short C program uses the sign of the NaN produced by dividing zero by zero to distinguish some x86 CPUs from ARM CPUs. A closing comment extends the joke, describing “1-bit floats” that can represent only NaN and Infinity.

Read on blog.coredump.cx3 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.