Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NaN different from NaN in Go?

Tags:

go

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.

like image 439
Alix Axel Avatar asked Jan 23 '26 22:01

Alix Axel


2 Answers

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.
like image 167
paxdiablo Avatar answered Jan 25 '26 19:01

paxdiablo


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.

like image 20
bazzargh Avatar answered Jan 25 '26 19:01

bazzargh