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

后端 未结 5 2074
误落风尘
误落风尘 2021-01-31 07:24

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         


        
5条回答
  •  情歌与酒
    2021-01-31 07:54

    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.

提交回复
热议问题