3

isNan is defined like this in iOS SDK, math.h as below,

#define isnan(x)                                                         \
    ( sizeof(x) == sizeof(float)  ? __inline_isnanf((float)(x))          \
    : sizeof(x) == sizeof(double) ? __inline_isnand((double)(x))         \
                                  : __inline_isnanl((long double)(x)))

And the inline function goes like this,

__header_always_inline int __inline_isnanf(float __x) {
    return __x != __x;
}

__header_always_inline is just to force the compiler to make the function surely inline.

What actually has been done in the inline function is pretty evasive to my eyes.

return __x != __x;

What does this line do? How does it verify if the argument is a NaN or not?

Edit:

The question here is NOT why NaN is not equal to NaN; but how its implemented. So please guide your answers towards the actual low level implementation.

Any help is greatly appreciated. Thanks.

Selvin
  • 12,333
  • 17
  • 59
  • 80
  • Related: [What is the rationale for all comparisons returning false for IEEE 754 NaN values?](http://stackoverflow.com/q/1565164) – jscs Apr 08 '14 at 06:43
  • 1
    "but how its implemented" -- I don't think you understand the question you're asking. Arithmetic on NaNs (and other floating point) is implemented in the microcode of your computer. Comparing a NaN to a NaN yields not equal ... because it does; because it's specified to. How is that implemented? By yielding not equal whenever NaNs are compared. There really isn't anything else to say about it. – Jim Balter Apr 08 '14 at 07:11

1 Answers1

2

CF http://en.wikipedia.org/wiki/NaN

A comparison with a NaN always returns an unordered result even when comparing with itself.

Mean a NaN is ALWAYS different from what you compare it too :)

I suppose the compiler/CPU has their own way to check for this special value, maybe someone can give a better answer than me about the implementation...

Antzi
  • 12,831
  • 7
  • 48
  • 74
  • 1
    And importantly, any number other than NaN is equal to itself. Yes, the FPU will just implement the IEEE 754 standard. – gnasher729 Apr 08 '14 at 07:00
  • "compiler/CPU has their own way to check for this special value" -- of course there is a way: the bit configurations for NaNs are well defined. But the compiler doesn't care; it's all done in the microcode of the floating point unit. – Jim Balter Apr 08 '14 at 07:15
  • @JimBalter it's all done in the microcode ... Is this statement valid for every architecture ? – Antzi Apr 08 '14 at 10:13