NaN different from NaN in Go?

huangapple go评论87阅读模式
英文:

NaN different from NaN in Go?

问题

有人能解释一下为什么会发生这种情况吗?http://play.golang.org/p/QTaHpUm5P7

很抱歉我没有将代码粘贴在这里,因为我现在在使用手机。

我知道我可以使用math.IsNaN()函数,但是我在所有的测试用例中都使用了比较运算符。

英文:

Can anyone explain why this happens? http://play.golang.org/p/QTaHpUm5P7

Apologies for not pasting the code here as well but I'm on mobile ATM.

I know I could use math.IsNaN() but I'm using the comparison operator for all my tests cases.

答案1

得分: 9

通常情况下,NaN 不被认为等于 任何 数字,包括它自己。这是因为它表示一个超出表示范围的数字。

因此,不能保证你没有两个不同的超出表示范围的数字,比如 0 / 0 和 -1 的平方根。

事实上,许多系统依赖于这个不等式来实现类似于 isNan() 的功能,如下所示:

define isNaN(x):
    return x != x

根据NaN Wikipedia 页面,IEEE 754 定义如下:

  • −∞ = −∞,
  • +∞ = +∞
  • 对于任何 x,包括 NaN,都有 x ≠ NaN
英文:

Generally, NaN is not considered equal to any number, including itself. That's because it represnts a number outside the range of representation.

Hence there's no guarantee that you don't have two different numbers outside the representation, such as 0 / 0 and the square root of -1.

In fact, many systems rely on this inequality to implement isNan() as something like:

define isNaN(x):
    return x != x

From the NaN Wikipedia page, IEEE 754 defines that:

  • −∞ = −∞,
  • +∞ = +∞ and
  • x ≠ NaN for any x, including NaN.

答案2

得分: 4

这是一个重复的问题,链接 https://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values 中解释了为什么在IEEE754中NaN永远不等于自身。

英文:

This is a duplicate of https://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values - NaN never equals itself in IEE754, the linked answer explains why.

huangapple
  • 本文由 发表于 2014年2月19日 10:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/21869571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定