Compare double to zero using epsilon

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

    An aproximation of epsilon (smallest possible difference) around a number (1.0, 0.0, ...) can be printed with the following program. It prints the following output:
    epsilon for 0.0 is 4.940656e-324
    epsilon for 1.0 is 2.220446e-16
    A little thinking makes it clear, that the epsilon gets smaller the more smaller the number is we use for looking at its epsilon-value, because the exponent can adjust to the size of that number.

    #include 
    #include 
    double getEps (double m) {
      double approx=1.0;
      double lastApprox=0.0;
      while (m+approx!=m) {
        lastApprox=approx;
        approx/=2.0;
      }
      assert (lastApprox!=0);
      return lastApprox;
    }
    int main () {
      printf ("epsilon for 0.0 is %e\n", getEps (0.0));
      printf ("epsilon for 1.0 is %e\n", getEps (1.0));
      return 0;
    }
    

提交回复
热议问题