Note that there are some explanatory texts on larger screens.

plurals
  1. POEquals and hashcode for vertices
    primarykey
    data
    text
    <p>I have a couple of vertices which I want to put into a Hashtable. Vertices which are really close to each other are considered as the same vertex. My C# vertex class looks like this:</p> <pre><code>public class Vertex3D { protected double _x, _y, _z; public static readonly double EPSILON = 1e-10; public virtual double x { get { return _x;} set { _x = value; } } public virtual double y { get { return _y; } set { _y = value; } } public virtual double z { get { 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 as 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 &gt; -EPSILON &amp;&amp; diffx &lt; EPSILON; bool eqy = diffy &gt; -EPSILON &amp;&amp; diffy &lt; EPSILON; bool eqz = diffz &gt; -EPSILON &amp;&amp; diffz &lt; EPSILON; return eqx &amp;&amp; eqy &amp;&amp; eqz; } public override int GetHashCode() { return this.x.GetHashCode() ^ this.y.GetHashCode() ^ this.z.GetHashCode(); } public override string ToString() { return "Vertex:" + " " + x + " " + y + " " + z; } </code></pre> <p>Now lets say I put the following two vertices into a dictionary (a dictionary is a hashtable which doesn't allow null keys):</p> <pre><code> Dictionary&lt;Vertex3D, Vertex3D&gt; vertexList = new Dictionary&lt;Vertex3D, Vertex3D&gt;(); Vertex3D v0 = new Vertex3D(0.000000000000000037842417475065449, -1, 0.00000000000000011646698526992202)); Vertex3D v1 = new Vertex3D(0, -1, 0)); vertexList.Add(v0, v0); vertexList.Add(v1, v1); </code></pre> <p>The problem is that my implementation of equals and hashcode is faulty. The above two vertices are considered as equal because the distance to each other is smaller than EPSILON. BUT they don't return the same hashcode.</p> <p>How do I implement equals and hashcode correctly?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload