使用Contains方法检查List中的float时的C#准确性

前端之家收集整理的这篇文章主要介绍了使用Contains方法检查List中的float时的C#准确性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个浮点列表,并想检查它是否已包含List.Contains()方法的特定值.我知道对于浮点相等测试,你经常不能使用==但是像myFloat这样的东西 – 值< 0.001. 我的问题是,Contains方法是否解释了这个或我是否需要使用一个方法来解释浮点精度错误,以便测试浮点数是否在列表中?

解决方法

来自 @L_502_0@的文档:

This method determines equality by using the default equality comparer,as defined by the object’s implementation of the 07001 method for T (the type of values in the list).

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

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");
    }
}

并使用它:

var result = floatList.Contains(100f,new FloatThresholdComparer(0.01f))
原文链接:https://www.f2er.com/css/242221.html

猜你在找的CSS相关文章