微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/css/242221.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。