21

Is it possible to check if a number is NaN or not?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
MBZ
  • 26,084
  • 47
  • 114
  • 191
  • 3
    NIL (NULL in C-ese) is a special *pointer* value. There is no such thing as NULL for numbers. Are you perhaps thinking of floating point NaNs? – zwol Aug 09 '10 at 03:04
  • I meant NaN, my bad, fixed the Q. – MBZ Aug 09 '10 at 03:08
  • 3
    Does this answer your question? [Checking if a double (or float) is NaN in C++](https://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c) – fernio Apr 20 '21 at 02:36

3 Answers3

31

Yes, by use of the fact that a NaN is not equal to any other number, including itself.

That makes sense when you think about what NaN means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.

So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They may be but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)

You can either look for a function (macro actually) like isnan (in math.h for C and cmath for C++) or just use the property that a NaN value is not equal to itself with something like:

if (myFloat != myFloat) { ... }

If, for some bizarre reason, your C implementation has no isnan (it should, since the standard mandates it), you can code your own, something like:

int isnan_float (float f) { return (f != f); }
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 2
    And do wrap `myFloat != myFloat` into some sort of `isnan` function with a comment, lest future readers that don't know about it be very confused. – GManNickG Aug 09 '10 at 03:11
7

Under Linux/gcc, there's isnan(double), conforming to BSD4.3.

C99 provides fpclassify(x) and isnan(x).
(But C++ standards/compilers don't necessarily include C99 functionality.)

There ought to be some way with std::numeric_limit<>... Checking...

Doh. I should have known... This question has been answered before... Checking if a double (or float) is NaN in C++ Using NaN in C++? http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan

Community
  • 1
  • 1
Mr.Ree
  • 8,320
  • 27
  • 30
-1

you are looking for null, but that is only useful for pointers. a number can't be null itself, it either has a known value that you put in there or random data from whatever was there in memory before.

Scott M.
  • 7,313
  • 30
  • 39