robertwessel2@yahoo.com
8/16/2011 5:46:00 AM
On Mon, 15 Aug 2011 21:45:19 -0700 (PDT), fl <rxjwg98@gmail.com>
wrote:
>On 15 août, 23:33, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
>> fl <rxjw...@gmail.com> writes:
>> > I encounter NaN often in Matlab. Recently, I use Matlab to generate
>> > some code for an embedded project. I get the following source code
>> > from Matlab below dot line.
>>
>> > I don't understand the line:
>> > c_y = (b_u != b_u);
>>
>> > Could you explain it to me? More specific, what result can get
>> > from: (b_u != b_u);?
>>
>> The != operator always gives 0 or 1 depending on the result of the
>> comparison. It's a not-equals comparison so it is asking if b_u is not
>> equal to itself. A NaNs won't compare equal to anything -- even another
>> NaN, so b_u != b_u is a way to ask if b_u is a NaN.
>>
>> <snip>
>> --
>> Ben.
>
>If NaN won't equal to anything, any number will not equal to itself
>either. I still do not understand b_u != b_u;
>
>ex:
>b_u = 3;
>(b_u!=b_u) ==> 1, right?
IEEE NaNs are special in a lot of ways. As Ben said, a NaN does not
compare equal to anything, even another NaN. An IEEE FP comparison is
*not* a direct comparison of the bit patterns of the two operands. A
NaN compared to anything else (including another NaN) also has no
order (IOW, "NaN > 3", "NaN == 3" and "NaN < 3" are *all* false, while
"NaN != 3" is true).
The "if (f != f)" trick works on many implementations using IEEE math
(all that I'm aware of), but it would probably be safer to use the
isnan() function provided by many implementations (and required by C99
- where it's a macro).