英文:
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:
−∞ = −∞,+∞ = +∞andx ≠ NaNfor anyx, includingNaN.
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论