使用Contains方法检查List <float>中的float时的C#精度

ogi*_*rry 6 c# contains list floating-accuracy

我有一个floats 列表,并想检查它是否已包含该List.Contains()方法的特定值.我知道,对于float相等测试,你经常不能使用==类似的东西myFloat - value < 0.001.

我的问题是,该Contains方法是否解释了这一点,或者我是否需要使用一种方法来解决float精度错误,以便测试浮点数是否在列表中?

Dav*_*idG 8

来自以下文档List(T).Contains:

此方法通过使用默认的相等比较器来确定相等性,由对象的IEquatable<T>.EqualsT方法实现(列表中的值类型)定义.

因此,您需要自己处理与阈值的比较.例如,您可以使用自己的自定义相等比较器.像这样的东西:

public class FloatThresholdComparer : IEqualityComparer<float>
{
    private readonly float _threshold;
    public FloatThresholdComparer(float threshold)
    {
        _threshold = threshold;
    }

    public bool Equals(float x, float y)
    {
        return Math.Abs(x-y) < _threshold;
    }

    public int GetHashCode(float f)
    {
        throw new NotImplementedException("Unable to generate a hash code for thresholds, do not use this for grouping");
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

var result = floatList.Contains(100f, new FloatThresholdComparer(0.01f))
Run Code Online (Sandbox Code Playgroud)