Why does nan == nan return false?

While experimenting with lua numbers I stumbled upon the following scenario:

local nan = math.sqrt(-1) --math.sqrt(-1) returns nan
print(nan) --should print nan
print(-nan) --should also print nan(not -nan)
print(nan == nan) --this prints false for some reason

Why does the last statement print false? I think this is the first time I encounter a lua variable that doesn’t equal to itself. Due to this I had to do the following workaround:

print(tostring(nan) == "nan")
1 Like

It’s because there are standards with comparisons being used by Roblox/Luau, and one of the standards is that any “unordered comparison” always returns false. Comparing with NaN is included in this, and so nan == nan is false.

I guess it kind of makes sense because well, it’s not meant to be a number to be ordered and compared among other numbers. Should math.sqrt(-1) == 0/0 return true?

Wikipedia explains this a lot more in depth: NaN - Wikipedia

2 Likes

Adding on to this: assembly - What does ordered / unordered comparison mean? - Stack Overflow

2 Likes

So basically the reason this doesn’t happen with -inf or inf is because negative and positive infinity are supposed to have a position on the number line(at the two extremeties) while this isn’t true for nan(we don’t know where it should be placed)?

1 Like

Pretty much, but personally I would say it’s because they have a known direction on the number line (lesser/greater than any number) instead of a position.

I would interpret NaN as “this is supposed to be treated as a number but it doesn’t belong on the number line so comparing it is useless”

1 Like

ok so i just read wikipedia and ill paraphrase what i took away from the comparisons

there are 3 main relationships with numbers (>, <, =) which will apply with most values, but NaN compared to NaN doesn’t follow any of these relationships, instead it follows a fourth relationship called unordered, which is why NaN == NaN returns false. it isn’t an equal relationship.