Can a near-zero floating value cause a divide-by-zero error?

neuviemeporte picture neuviemeporte · Aug 24, 2012 · Viewed 15.8k times · Source

Everybody knows you're not supposed to compare floats directly, but rather using a tolerance:

float a,b;
float epsilon = 1e-6f;
bool equal = (fabs(a-b) < epsilon);

I was wondering if the same applies to comparing a value to zero before using it in division.

float a, b;
if (a != 0.0f) b = 1/a; // oops?

Do I also need to compare with epsilon in this case?

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Aug 24, 2012

Floating point division by zero is not an error. It raises a floating point exception (which is a no-op unless you're actively checking them) on implementations that support floating point exceptions, and has well-defined result: either positive or negative infinity (if the numerator is nonzero), or NAN (if the numerator is zero).

It's also possible to get infinity (and an overflow exception) as the result when the denominator is nonzero but very close to zero (e.g. subnormal), but again this is not an error. It's just how floating point works.

Edit: Note that, as Eric has pointed out in the comments, this answer assumes the requirements of Annex F, an optional part of the C standard detailing floating point behavior and aligning it with the IEEE standard for floating point. In the absence of IEEE arithmetic, C does not define floating point division by zero (and in fact, the results of all floating point operations are implementation-defined and may be defined as complete nonsense and still conform to the C standard), so if you're dealing with an outlandish C implementation that does not honor IEEE floating point, you'll have to consult the documentation for the implementation you're using to answer this question.