c# - Equals and hashcode for vertices -


i have couple of vertices want put hashtable. vertices close each other considered same vertex. c# vertex class looks this:

public class vertex3d {     protected double _x, _y, _z;     public static readonly double epsilon = 1e-10;      public virtual double x      {         { return _x;}         set { _x = value; }     }      public virtual double y     {         { return _y; }         set { _y = value; }     }      public virtual double z     {         { return _z; }         set { _z = value; }     }      public vertex3d(double p1, double p2, double p3)     {         this._x = p1;         this._y = p2;         this._z = p3;     }      public override bool equals(object obj)     {         var other = obj vertex3d;          if (other == null)         {             return false;         }         double diffx = this.x - other.x;         double diffy = this.y - other.y;         double diffz = this.z - other.z;         bool eqx = diffx > -epsilon && diffx < epsilon;         bool eqy = diffy > -epsilon && diffy < epsilon;         bool eqz = diffz > -epsilon && diffz < epsilon;         return eqx && eqy && eqz;     }      public override int gethashcode()     {         return this.x.gethashcode() ^ this.y.gethashcode() ^ this.z.gethashcode();     }      public override string tostring()     {         return "vertex:" + " " + x + " " + y + " " + z;     } 

now lets put following 2 vertices dictionary (a dictionary hashtable doesn't allow null keys):

    dictionary<vertex3d, vertex3d> vertexlist = new dictionary<vertex3d, vertex3d>();     vertex3d v0 = new vertex3d(0.000000000000000037842417475065449, -1,   0.00000000000000011646698526992202));     vertex3d v1 = new vertex3d(0, -1, 0));     vertexlist.add(v0, v0);     vertexlist.add(v1, v1); 

the problem implementation of equals , hashcode faulty. above 2 vertices considered equal because distance each other smaller epsilon. don't return same hashcode.

how implement equals , hashcode correctly?

hashtables require equivalence classes, equals() not transitive. therefore cannot use hashtable purpose. (if, example, allowed nearby objects compare equal rounding lattice points, have transitivity , equivalence classes. there still arbitrarily close points, down precision of representation, fell on opposite sides of threshold , in different equivalence classes)

there other data structures, such octtrees, designed accelerate finding nearby points. suggest use 1 of those.


Comments