Tim*_*sen 5 c# floating-point precision hashcode
我之前已经问了一个关于这个课程的问题,但这里又是一个问题.
我创建了一个Complex类:
public class Complex
{
public double Real { get; set; }
public double Imaginary { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我正在实现Equals和Hashcode函数,而Equal函数考虑了一定的精度.我使用以下逻辑:
public override bool Equals(object obj)
{
//Some default null checkint etc here, the next code is all that matters.
return Math.Abs(complex.Imaginary - Imaginary) <= 0.00001 &&
Math.Abs(complex.Real - Real) <= 0.00001;
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,当虚构和真实部分彼此非常接近时,它说它们是相同的.
现在我正在尝试实现HashCode函数,我已经使用了一些John skeet在这里使用的示例,目前我有以下内容.
public override int GetHashCode()
{
var hash = 17;
hash = hash*23 + Real.GetHashCode();
hash = hash*23 + Imaginary.GetHashCode();
return hash;
}
Run Code Online (Sandbox Code Playgroud)
但是,这并没有考虑我想要使用的某些精度.所以基本上是以下两个类:
Complex1[Real = 1.123456; Imaginary = 1.123456]
Complex2[Real = 1.123457; Imaginary = 1.123457]
是Equal,但不提供相同的HashCode,我怎么能做到这一点?