Compare double to zero using epsilon

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

    There are numbers that exist between 0 and epsilon because epsilon is the difference between 1 and the next highest number that can be represented above 1 and not the difference between 0 and the next highest number that can be represented above 0 (if it were, that code would do very little):-

    #include 
    
    int main ()
    {
      struct Doubles
      {
          double one;
          double epsilon;
          double half_epsilon;
      } values;
    
      values.one = 1.0;
      values.epsilon = std::numeric_limits::epsilon();
      values.half_epsilon = values.epsilon / 2.0;
    }
    

    Using a debugger, stop the program at the end of main and look at the results and you'll see that epsilon / 2 is distinct from epsilon, zero and one.

    So this function takes values between +/- epsilon and makes them zero.

提交回复
热议问题