c – Division by zero for float variables

Question:

if I have

float v = v();
float h = h();

and then I want to check a condition like this:

if (v<0 && ABS(v/h) > 0.5)

then can I be sure that if

h==0, то ABS(v/h) == INFINITY и INFINITY точно > 0.5?

That is, is it not necessary to take into account that h can be equal to 0, like this:

if (h==0 ? v<0 : v<0 && ABS(v/h) > 0.5)

?

Answer:

Partially yes. Floating point numbers obey the IEEE-754 standard .

  1. If v > 0 and h == 0 then v/h == INFINITY . It is guaranteed that INFINITY > 0.5 .
  2. If v < 0 and h == 0 then v/h == -INFINITY . For him, -INFINITY < 0.5 .
  3. If v == 0 and h == 0 , then v/h == NaN . For it, any comparison, EMNIP, returns false.

Operations on infinite values ​​are strictly defined in the C standard IEEE-754. So your code is correct.


When working with floating point, control over division by zero is disabled by default, and division by zero gives infinity or NaN. There is, however, a method to enable such controls. However, even in this case, when dividing by zero, an exception or some other error will not occur, but only a flag will be set, which can be interrogated by calling fetestexcept(FE_DIVBYZERO) .


You might find the atan2 function useful:

float angle = atan2(h, w);
if (angle < -2*PI/3 && angle > -PI/3) ...
Scroll to Top