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.
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>
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>
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!