哈希码实现双精度 [英] Hashcode implementation double precision

查看:115
本文介绍了哈希码实现双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问一个关于此类问题之前,但在这里一个试。

I've asked a question about this class before, but here is one again.

我已经创建了一个复杂的类:

I've created a Complex class:

 public class Complex
 {
        public double Real { get; set; }
        public double Imaginary { get; set; }
 }

和我实施等于 Hashcode方法的功能,并在账户平等的功能需要一定的精度。我用下面的逻辑是:

And I'm implementing the Equals and the Hashcode functions, and the Equal function takes in account a certain precision. I use the following logic for that:

    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;
    }



好工作的,当虚和实部是真正接近每其他,它说它们是相同的。

Well this works, when the Imaginary and the Real part are really close to each other, it says they are the same.

现在我是想实现hashCode功能,我使用了一些例子用在这里约翰飞碟,目前我有以下几点。

Now I was trying to implement the HashCode function, I've used some examples John skeet used here, currently I have the following.

    public override int GetHashCode()
    {
        var hash = 17;
        hash = hash*23 + Real.GetHashCode();
        hash = hash*23 + Imaginary.GetHashCode();
        return hash;
    }



不过,这并不需要在占了一定精度我想要使用。所以基本上以下两类:

However, this does not take in account the certain precision I want to use. So basically the following two classes:

Complex1 [实时= 1.123456;虚= 1.123456]

Complex2 [实时= 1.123457;虚= 1.123457]

等于,但不提供相同的的hashCode ,我怎么能做到这一点?

Are Equal but do not provide the same HashCode, how can I achieve that?

推荐答案

首先,你的的equals()的实施被打破了。读到这里 来看看为什么。

First of all, your Equals() implementation is broken. Read here to see why.

二,这样的模糊等于断合同的equals()(它是不可传递的,一件事),这样的使用它与的Hashtable 将无法正常工作,不管你如何实现的GetHashCode()

Second, such a "fuzzy equals" breaks the contract of Equals() (it's not transitive, for one thing), so using it with Hashtable will not work, no matter how you implement GetHashCode().

对于这种事情,你真的需要一个空间索引,如 R树

For this kind of thing, you really need a spatial index such as an R-Tree.

这篇关于哈希码实现双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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