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) < eps
Do I also need to compare with epsilon in this case?
You won't ever receive a divide by zero error, as 0.0f
is represented exactly in an IEEE float.
That being said you may still want to use some tolerance - though this depends completely on your application. If the "zero" value is the result of other math, it's possible to get a very small, non-zero number, which may cause an unexpected result after your division. If you want to treat "near zero" numbers as zero, a tolerance would be appropriate. This completely depends on your application and goals, however.
If your compiler is using IEEE 754 standards for exception handling, then divide by zero, as well as a division by a value which is small enough to cause an overflow, would both result in a value of +/- infiniti. This could mean that you could want to include the check for very small numbers (that would cause an overflow on your platform). For example, on Windows, float
and double
both conform to the specifications, which could cause a very small divisor to create +/- infiniti, just like a zero value.
If your compiler/platform is not following IEEE 754 floating point standards, then I believe the results are platform specific.