我有一个清单float
s 并想要检查它是否已经包含特定值List.Contains()
方法。我知道对于float
您经常无法使用的相等性测试==
但类似的东西myFloat - value < 0.001
.
我的问题是,Contains
方法说明了这一点,或者我需要使用一种说明方法float
用于测试浮点数是否在列表中的精度错误?
从文档中List(T).Contains https://msdn.microsoft.com/en-us/library/bhkz42b3(v=vs.110).aspx:
此方法通过使用默认的相等比较器来确定相等性,该比较器由对象的实现所定义IEquatable<T>.Equals https://msdn.microsoft.com/en-us/library/ms131190(v=vs.110).aspxT 的方法(列表中值的类型)。
因此,您需要自己处理与阈值的比较。例如,您可以使用自己的自定义相等比较器。像这样的事情:
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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)