Compare double to zero using epsilon

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

    The difference between X and the next value of X varies according to X.
    epsilon() is only the difference between 1 and the next value of 1.
    The difference between 0 and the next value of 0 is not epsilon().

    Instead you can use std::nextafter to compare a double value with 0 as the following:

    bool same(double a, double b)
    {
      return std::nextafter(a, std::numeric_limits::lowest()) <= b
        && std::nextafter(a, std::numeric_limits::max()) >= b;
    }
    
    double someValue = ...
    if (same (someValue, 0.0)) {
      someValue = 0.0;
    }
    

提交回复
热议问题