Comparing IEEE floats and doubles for equality

前端 未结 15 2357
南方客
南方客 2020-11-30 06:00

What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.

15条回答
  •  感动是毒
    2020-11-30 07:03

    The current version I am using is this

    bool is_equals(float A, float B,
                   float maxRelativeError, float maxAbsoluteError)
    {
    
      if (fabs(A - B) < maxAbsoluteError)
        return true;
    
      float relativeError;
      if (fabs(B) > fabs(A))
        relativeError = fabs((A - B) / B);
      else
        relativeError = fabs((A - B) / A);
    
      if (relativeError <= maxRelativeError)
        return true;
    
      return false;
    }
    

    This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?

提交回复
热议问题