tags:

views:

75

answers:

3

Hi, i have issue with comparing NAN value in C++, Visualstudio. I need to handle Division by Zero in my code. if i get division by zero, i want to assign NAN to the result. Check at later point of time, whether result has NAN. But NAN comparision is failing at later point of time, even though i assign quiet_Nan() as below.

double d = std::numeric_limits<double>::quiet_NaN();
if( d == std::numeric_limits<double>::quiet_NaN())
{
    cout<<" NAN ";
}
else
{
    cout<<" Number";
}

I know that floating values can't be compared for equality. I tried taking diff between d and quiet_Nan() and tried to compare it with floating number with < operator. I saw few posts but couldn't get how to compare double value.

how to know the existence of NAN value in a double variable ?

+2  A: 

Having no experience in C++ whatsoever, but instead of:

if( d == std::numeric_limits::quiet_NaN())

you should call:

if(std::numeric_limits::quiet_isNaN(d))

if such a method exists.

keep in mind that if 'd' is NaN, d==d evaluates to FALSE

Riven
Yes. `is_nan` or the language equivalent is the way. NaN is per definition always != anything else, even itself.
calmh
@Riven: quiet_isNan() method is not available. I am using VS2008.
bjskishore123
You shouldn't care whether it's a quiet nan when testing. isnan() should be enough.
MSalters
Note that the `(x != x)` trick is by far the most portable.
MSalters
+2  A: 

I don't think the current standard library provides any is_nan implementation you will need to use a 3rd party lib or roll your own

floating point values can be compared for equality, it is just rarely useful, but this is a one of those places where it is useful, what you want is something like:

template <T>
bool is_nan(T d)
{
  return std::numeric_limits<T>::has_quiet_NaN && d != d;
}

which checks that you have an appropriate NaN value on your machine and then uses the fact that NaN != NaN is true!

boost propbably should provided this somewhere?

jk
A: 

I found your info on Microsoft's documentation page:

http://msdn.microsoft.com/en-us/library/w22adx1s.aspx

Try something like

if(myDouble != myDouble)
{
   // myDouble is NaN
}
else
{
   // myDouble is NOT NaN
}

This should do the trick.

paercebal