Double Hashcode Implementation Accuracy

I asked a question about this class before, but here is another one.

I created the Complex class:

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

And I implement the functions Equalsand Hashcode, and the Equal function takes into account a certain accuracy. To do this, I use the following logic:

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

It's good that this works when the Imaginary and Real parts are really close to each other, they are said to be the same.

Now I tried to implement the HashCode function, I used some examples of using John skeet here, I currently 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 into account the specific accuracy that I want to use. So basically the following two classes:

Complex1[Real = 1.123456; Imaginary = 1.123456]

Complex2[Real = 1.123457; Imaginary = 1.123457]

Are Equal, but do not provide the same Hashcode, how can I achieve this?

+5
4

, Equals() . , , .

-, " " Equals() ( , ), , Hashtable, , , GetHashCode().

, R-Tree.

+5

.

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

5 -

+1

:

  • Decimal double
  • Instead of using Real.GetHashCode, use Real.RoundTo6Ciphers (). GetHashCode ().

Then you will have the same hash code.

+1
source

I would create read-only properties that around Real and Imaginary reach hundredths of a thousand, and then execute the equals and hashcode values ​​on these getter properties.

0
source

All Articles