Home >Backend Development >C++ >How Should Double.Epsilon Be Used for Accurate Floating-Point Comparisons?
Question:
The MSDN documentation for System.Double.Epsilon states that it should not be used as the margin of difference for determining equality. How should Double.Epsilon be used for floating-point comparisons?
Answer:
The MSDN statement is misleading. Double.Epsilon represents the smallest non-zero representable floating-point value. Therefore, it can be used as the epsilon in the examples provided in the Stack Overflow thread "What is the most effective way for float and double comparison?"
For equality, a suitable epsilon can be estimated as Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15, where x and y are the double values being compared. However, it's important to note that truncation errors can accumulate, so a larger epsilon may be necessary when comparing computed values.
To implement equality, greater than, less than, less than or equal to, and greater than or equal to, the following code can be used:
public static bool AboutEqual(double x, double y) { double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15; return Math.Abs(x - y) <= epsilon; } public static bool GreaterThan(double x, double y) { double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15; return x > y + epsilon; } public static bool LessThan(double x, double y) { double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15; return x < y - epsilon; } public static bool LessThanOrEqualTo(double x, double y) { double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15; return x <= y + epsilon; } public static bool GreaterThanOrEqualTo(double x, double y) { double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15; return x >= y - epsilon; }
The above is the detailed content of How Should Double.Epsilon Be Used for Accurate Floating-Point Comparisons?. For more information, please follow other related articles on the PHP Chinese website!