Compare double to zero using epsilon

后端 未结 11 1382
醉梦人生
醉梦人生 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:16

    Suppose we are working with toy floating point numbers that fit in a 16 bit register. There is a sign bit, a 5 bit exponent, and a 10 bit mantissa.

    The value of this floating point number is the mantissa, interpreted as a binary decimal value, times two to the power of the exponent.

    Around 1 the exponent equals zero. So the smallest digit of the mantissa is one part in 1024.

    Near 1/2 the exponent is minus one, so the smallest part of the mantissa is half as large. With a five bit exponent it can reach negative 16, at which point the smallest part of the mantissa is worth one part in 32m. And at negative 16 exponent, the value is around one part in 32k, much closer to zero than the epsilon around one we calculated above!

    Now this is a toy floating point model that does not reflect all the quirks of a real floating point system , but the ability to reflect values smaller than epsilon is reasonably similar with real floating point values.

提交回复
热议问题