检查List< float>中的float时的C#精度与包含方法 [英] C# accuracy when checking float in List<float> with Contains method

查看:89
本文介绍了检查List< float>中的float时的C#精度与包含方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of floats and want to check if it already contains a particular value with the List.Contains() method. I know that for float equality tests you often can't use == but something like myFloat - value < 0.001.

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

My question is, does the Contains method account for this or I do I need to use a method that accounts for float precision errors for testing if the float is in the list?

推荐答案

此方法通过使用默认的相等比较器来确定相等,该比较器由对象的

This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable<T>.Equals method for T (the type of values in the list).

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

So you will need to handle comparison with a threshold yourself. For example, you can use your own custom equality comparer. Something like this:

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

这篇关于检查List&lt; float&gt;中的float时的C#精度与包含方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆