3

Suppose I'm evaluating a / b where a and b are both floating point types.

If b is zero then the answer is -1.#IND.

Are there any any other values of b (and a) that will give me -1.#IND, or is checking for non-zero b sufficient in order to avoid getting this result?

Possibly not relevant, but I'm coding in C++.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • 1
    What exactly is -1.#IND? – Leo Chapiro Jan 08 '15 at 14:44
  • The result of 1.0 / 0.0, say. – P45 Imminent Jan 08 '15 at 14:45
  • Mathematically, zero is the only value causing problem so I guess that should be the only one in C++ too. – Laurent S. Jan 08 '15 at 14:46
  • Related: http://stackoverflow.com/q/347920/1207195 – Adriano Repetti Jan 08 '15 at 14:47
  • @SlodgeMonster if you can obtain that value as 1.0 / 0.0, you might also obtain it as 1e300 / 1e-300, although 1e-300 is not 0. You had better check what result this division produces. – Pascal Cuoq Jan 08 '15 at 14:48
  • If one operand is a nan then the result if I remember right is supposed to be a nan as well. If the divisor is zero then there are rules on that being a properly signed infinity or maybe a signaling nan, etc...See the IEEE floating point spec. If you are not using IEEE float on your system then you need to read up on the floating point system you are using to find out if there are other operands – old_timer Jan 08 '15 at 15:04
  • 1
    @duDE: -1.#IND is a particular QNaN encoding, INDEFINITE. If I recall correctly, the specific bit pattern is 0xffc0000 for single precision, and 0xfff8000000000000 for double precision. – njuffa Jan 08 '15 at 16:40

2 Answers2

3

From C++11 and onwards you can perform the calculation confidently, using something along the lines of

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

Pre C++11, you might get away with comparing the result with itself,

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

But that could fail if your compiler doesn't use IEEE floating point (the C++ standard does not insist on that). It can also fail if compiled with floating point optimisations switched on.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Check b != 0 and neither a nor b have to be NaN or Infinite. Then your division will be out of those errors. But you still can get precision problems.

Joshua Behrens
  • 818
  • 13
  • 23