MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# Why is NaN not equal to NaN

Asked by Michael on 16 Jan 2013

Why is this not true?

NaN==NaN

ans =

`     0`

## Products

No products are associated with this question.

Answer by Cedric Wannaz on 16 Jan 2013
Edited by Cedric Wannaz on 16 Jan 2013

Most times, you don't want this test to return true indeed. Imagine testing a==b and having a true result when both a and b are undefined; this would make little sense. It is the same with NaN.

While it is not the original question, note that you can test equality assuming NaN 's are equal:

http://www.mathworks.com/help/matlab/ref/isequalwithequalnans.html

But with that you usually want to test if "behaviors" are the same (and not equality per se), e.g. if two functions return the same number or both NaN do something, else do something else.

Matt J on 16 Jan 2013

Although more recently, isequalwithequalnans has been deprecated in favor of isequaln

http://www.mathworks.com/help/matlab/ref/isequaln.html

Cedric Wannaz on 16 Jan 2013

Ah thank you, I still have 2011b and I wasn't aware (despite linking the doc for 2012b ;-/).

Answer by Matt J on 16 Jan 2013
Edited by Matt J on 16 Jan 2013

Because equality is a notion applied to numbers. How can 2 things be equal when they are not numbers?

Cedric Wannaz on 16 Jan 2013

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 Wannaz 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!