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

后端 未结 5 2083
误落风尘
误落风尘 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:48

    Only a division by exactly 0.f will raise a division by zero exception.

    However, division by a really small number can generate an overflow exception - the result is so large that it no longer can be represented by a float. The division will return infinity.

    The float representation of infinity can be used in calculations so there might not be a need to check for it if the rest of your implementation can handle it.

提交回复
热议问题