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

我有一个浮点列表,并想检查它是否已包含List.Contains()方法的特定值.我知道对于浮点相等测试,你经常不能使用==但是像myFloat这样的东西 – 值< 0.001. 我的问题是,Contains方法是否解释了这个或我是否需要使用一个方法来解释浮点精度错误,以便测试浮点数是否在列表中?

解决方法

来自 List(T).Contains的文档:

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))

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效