Home > Backend Development > C++ > How Should Double.Epsilon Be Used for Accurate Floating-Point Comparisons?

How Should Double.Epsilon Be Used for Accurate Floating-Point Comparisons?

Patricia Arquette
Release: 2025-01-06 03:28:43
Original
905 people have browsed it

How Should Double.Epsilon Be Used for Accurate Floating-Point Comparisons?

Double.Epsilon for Float and Double 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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template