C# 的浮点比较函数

时间:2023-05-05
本文介绍了C# 的浮点比较函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

有人可以指出(或展示)C# 中一些很好的通用浮点比较函数来比较浮点值吗?我想为 IsEqualIsGreaterIsLess 实现函数.我也只关心双打而不是花车.

Can someone point towards (or show) some good general floating point comparison functions in C# for comparing floating point values? I want to implement functions for IsEqual, IsGreater an IsLess. I also only really care about doubles not floats.

推荐答案

编写一个有用的通用浮点 IsEqual 非常非常困难,如果不是完全不可能的话.对于 a==0,您当前的代码将严重失败.该方法在这种情况下的行为方式实际上是一个定义问题,并且可以说代码最好针对特定的域用例进行定制.

Writing a useful general-purpose floating point IsEqual is very, very hard, if not outright impossible. Your current code will fail badly for a==0. How the method should behave for such cases is really a matter of definition, and arguably the code would best be tailored for the specific domain use case.

对于这种事情,你真的,真的需要一个好的测试套件.这就是我为浮点指南所做的,这就是我想出的最后加上(Java 代码,应该很容易翻译):

For this kind of thing, you really, really need a good test suite. That's how I did it for The Floating-Point Guide, this is what I came up with in the end (Java code, should be easy enough to translate):

public static boolean nearlyEqual(float a, float b, float epsilon) {
    final float absA = Math.abs(a);
    final float absB = Math.abs(b);
    final float diff = Math.abs(a - b);

    if (a == b) { // shortcut, handles infinities
        return true;
    } else if (a == 0 || b == 0 || absA + absB < Float.MIN_NORMAL) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < (epsilon * Float.MIN_NORMAL);
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

您还可以在网站上找到测试套件.

You can also find the test suite on the site.

附录:在 c# 中用于双打的相同代码(如问题中所问)

Appendix: Same code in c# for doubles (as asked in questions)

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))
    { // shortcut, handles infinities
        return true;
    } 
    else if (a == 0 || b == 0 || absA + absB < MinNormal) 
    {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < (epsilon * MinNormal);
    }
    else
    { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

这篇关于C# 的浮点比较函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:没有科学记数法的双精度字符串转换 下一篇:如何用浮点数和小数表示 0.1

相关文章

最新文章