Why is NaN not equal to NaN
Show older comments
Why is this not true?
NaN==NaN
ans =
0
Accepted Answer
More Answers (1)
Because equality is a notion applied to numbers. How can 2 things be equal when they are not numbers?
7 Comments
Walter Roberson
on 16 Jan 2013
Not true. For example, 'A' == 'A', and equality of data structures can be defined.
A comparison with a NaN always returns an unordered result even when comparing with itself.
Matt J
on 16 Jan 2013
I would argue, though, that 'A' could be considered a number.
I would also argue that the definition that you cite is motivated precisely by the fact that NaN is not to be considered a number and therefore not meant to have inter-comparison operations that numbers typically have.
I would argue that 'A'=='A' is testing actually numerical equality of ascii codes, hence numbers.
To illustrate
>> 'A'==65
ans = 1
Or let say that I have the impression that each time my lhs/rhs could not be directly typecast-ed into numbers, I had to use a more elaborate test, like isequal().
Walter Roberson
on 17 Jan 2013
Cedric: MATLAB does not use ASCII. If it did, it would not be possible to use any codepoint above 127. MATLAB uses a custom 16 bit coding that is the same as UTF-16-BE up until (I think it is) 0xBFFF (from 0xC000 onward signals additional bytes in UTF-16 but not in MATLAB's coding.)
MATLAB's == operator (eq) is defines specifically with
eq(A, B) is called for the syntax A == B when either A or B is an object.
thus allowing for the possibility of comparison being held equal when the numeric representations are not identical.
Matt: NaN could, I think, have been defined as comparing equal to itself, and I don't think much would have changed, except for the question of whether various NaN are equal to each other. (NaN is not a single value: there are something like 2^50 different Quiet NaN, and the same number of Signalling NaN; the NaN issued was intended to reflect the reason the NaN was generated, such as inf - inf giving a different NaN than inf * 0 -- so you would still want to be using isnan() rather than comparing to a particular NaN.)
Cedric
on 17 Jan 2013
Thank you for your comment, Walter. I meant ASCII having extended ASCII in mind (8bits), and I never realized that it was 16 bits UTF-like indeed!
math man
on 17 Sep 2021
You might wonder, though, why NaN ~= NaN returns true?
That is, if they are not numbers why are they compared in this case to give a misleading result?
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!