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

问题描述

可有人向(或节目),在C#中一些很好的通用浮点比较函数用于比较浮点值点?我想要实现的ISEQUAL功能,IsGreater的IsLess。我也才真正地关心双打不浮动。

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.

编辑:我去掉了原code,因为它是完整的垃圾。见接受的答案。

I removed the original code since it was complete junk. See the accepted answer.

推荐答案

写一个有用的通用浮点 ISEQUAL 是非常,非常努力,如果不是完全不可能的。您当前的code会失败很糟糕的 A == 0 。如何方法应该表现为这样的情况下,确实是定义的问题,可以说是code将最好是专门针对特定领域的使用情况。

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的code,应该很容易翻译):

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 || diff < 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;
        }
    }

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

附录:同code在C#中的双打(如问问题)

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

public bool NearlyEqual(double a, double b, double epsilon)
{
    double absA = Math.Abs(a);
    double absB = Math.Abs(b);
    double diff = Math.Abs(a - b);

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

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

07-26 04:13