C++ FAQ Celebrating Twenty-One Years of the C++ FAQ!!!
(Click here for a personal note from Marshall Cline.)
Section 29:
[29.15] What is this NaN thing?

NaN means "not a number," and is used for floating point operations.

There are lots of floating point operations that don't make sense, such as dividing by zero, taking the log of zero or a negative number, taking the square root of a negative number, etc. Depending on your compiler, some of these operations may produce special floating point values such as infinity (with distinct values for positive vs. negative infinity) and the not a number value, NaN.

If your compiler produces a NaN, it has the unusual property that it is not equal to any value, including itself. For example, if a is NaN, then a == a is false. In fact, if a is NaN, then a will be neither less than, equal to, nor greater than any value including itself. In other words, regardless of the value of b, a < b, a <= b, a > b, a >= b, and a == b will all return false.

Here's how to check if a value is NaN:

#include <cmath>

void funct(double x)
{
  if (isnan(x)) {    though see caveat below
    // x is NaN
    ...
  } else {
    // x is a normal value
    ...
  }
}
Note: although isnan() is part of the latest C standard library, your C++ compiler vendor might not supply it. For example, Microsoft Visual C++.NET does not supply isnan() (though it does supply _isnan() defined in <float.h>). If your vendor does not supply any variant of isnan(), define this function:
inline bool my_isnan(double x)
{
  return x != x;
}
In any case, DO NOT WRITE ME just to say that your compiler does/does not support isnan().