Home > Backend Development > C++ > How to Reliably Compare Floating-Point Numbers in C#?

How to Reliably Compare Floating-Point Numbers in C#?

Linda Hamilton
Release: 2025-01-23 10:56:10
Original
738 people have browsed it

How to Reliably Compare Floating-Point Numbers in C#?

C# floating point comparison function

In C#, comparison of floating point numbers can present challenges due to their inherent precision limitations. To solve this problem, consider implementing a custom comparison function.

IsEqual function

Writing a generic IsEqual function for floating point values ​​can be challenging. A common approach is to use a tolerance threshold, or epsilon. For example:

<code class="language-csharp">public static bool NearlyEqual(double a, double b, double epsilon)
{
    const double MinNormal = 2.2250738585072014E-308d;
    double absA = Math.Abs(a);
    double absB = Math.Abs(b);
    double diff = Math.Abs(a - b);

    // 处理特殊情况(例如,无穷大)
    if (a.Equals(b))
        return true;

    // 考虑 a 或 b 接近零的情况
    if (a == 0 || b == 0 || absA + absB < MinNormal)
        return diff < epsilon;

    // 使用相对误差
    return diff / (absA + absB) < epsilon;
}</code>
Copy after login

IsGreater and IsLess functions

The method of implementing IsGreater and IsLess functions is similar:

<code class="language-csharp">public static bool IsGreater(double a, double b, double epsilon)
{
    // 处理特殊情况
    if (a.CompareTo(b) > 0)
        return true;
    if (a.CompareTo(b) == 0)
        return false;

    // 对非零情况使用相对误差
    double diff = a - b;
    double absA = Math.Abs(a);
    double absB = Math.Abs(b);
    return diff / (absA + absB) > epsilon;
}

public static bool IsLess(double a, double b, double epsilon)
{
    // IsGreater 的反向操作
    return IsGreater(b, a, epsilon);
}</code>
Copy after login

These functions provide a useful way to compare floating point values ​​in C# while taking into account their inherent precision limitations.

The above is the detailed content of How to Reliably Compare Floating-Point Numbers in C#?. 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