Whether division by any number other than zero will be -1. # IND

Suppose I am evaluating a / b

where a

and b

are both floating point types.

If b

zero, then the answer is -1. # IND.

Are there any other value b

(s a

) that would give me -1. # IND or check for non-zero b

to avoid getting this result?

It may not be relevant, but I am coding in C ++.

+3


source to share


2 answers


From C ++ 11 onwards, you can perform the calculation with confidence using something in strings

std::isnan(x = a / b);

Pre C ++ 11, you can get away with comparing the result with yourself,



bool is_nan(double x)
{
    return x != x; 
}

      

But it can crash if your compiler does not use IEEE floating points (the C ++ standard does not insist on this). It can also crash if compiled with floating point optimizations.

+3


source


Check b! = 0 and neither a nor b should be NaN or Infinite . Then your division will be from these mistakes. But you can still get accuracy problems.



+1


source







All Articles