如果它浮起来
If It Floats

原始链接: https://blog.coredump.cx/p/if-it-floats

这段文字幽默地探讨了浮点数的怪异之处:无效运算会得到 ±Infinity 或 NaN。NaN 永不等于自身,而 Infinity 会。NaN 会在算术运算中传播。奇特性包括 C 将 NaN 视为真值、JavaScript 将 NaN 视为假值,以及 ~NaN 等于 ~Infinity。JavaScript 的数字是浮点数,导致无限循环和稀疏数组索引,其中 NaN 是一个等于自身的有效索引。在 C 中,NaN 可以是正的或负的,用于检测仿制 CPU。总体而言,这是一篇轻松有趣的计算边界案例之旅。

Hacker News 新 | 过去 | 评论 | 提问 | 展示 | 工作 | 提交 登录 如果它能浮起 ( coredump.cx ) 42 分 由 surprisetalk 3 小时前 | 过去 | 收藏 | 2 条评论 帮助 arcastroe 21 分钟前 | 下一个 [–] 让我想起几年前看过的“Wat”闪电演讲: https://www.destroyallsoftware.com/talks/wat 回复 dmitrygr 22 分钟前 | 上一个 [–] 精彩且写得非常好。 回复 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

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.

联系我们 contact @ memedata.com