Compare double to zero using epsilon

后端 未结 11 1373
醉梦人生
醉梦人生 2020-11-29 15:54

Today, I was looking through some C++ code (written by somebody else) and found this section:

double someValue = ...
if (someValue <  std::numeric_limits&         


        
11条回答
  •  佛祖请我去吃肉
    2020-11-29 16:20

    Assuming 64-bit IEEE double, there is a 52-bit mantissa and 11-bit exponent. Let's break it to bits:

    1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^0 = 1
    

    The smallest representable number greater than 1:

    1.0000 00000000 00000000 00000000 00000000 00000000 00000001 × 2^0 = 1 + 2^-52
    

    Therefore:

    epsilon = (1 + 2^-52) - 1 = 2^-52
    

    Are there any numbers between 0 and epsilon? Plenty... E.g. the minimal positive representable (normal) number is:

    1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^-1022 = 2^-1022
    

    In fact there are (1022 - 52 + 1)×2^52 = 4372995238176751616 numbers between 0 and epsilon, which is 47% of all the positive representable numbers...

提交回复
热议问题