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

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

    To answer the question in the title of your post, dividing by a very small number will not cause a division by zero, but it may cause the result to become an infinity:

    double x = 1E-300;
    cout << x << endl;
    double y = 1E300;
    cout << y << endl;
    double z = y / x;
    cout << z << endl;
    cout << (z == std::numeric_limits::infinity()) << endl;
    

    This produces the following output:

    1e-300
    1e+300
    inf
    1
    

提交回复
热议问题