3

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.

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • possible duplicate of [What is the rationale for all comparisons returning false for IEEE754 NaN values?](http://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values) – fuz Feb 19 '14 at 12:25

2 Answers2

9

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.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    well, guess how isNan() is implemented in Go? http://golang.org/src/pkg/math/bits.go?h=IsNaN#L31 – rob74 Feb 19 '14 at 15:54
4

This is a duplicate of What is the rationale for all comparisons returning false for IEEE754 NaN values? - NaN never equals itself in IEE754, the linked answer explains why.

Community
  • 1
  • 1
bazzargh
  • 1,792
  • 10
  • 16