This question is similar to the one here.
We all know what PointF is, don’t we? This is the data structure:
public struct PointF
{
public float X;
public float Y;
}
How to implement IEqualityComparer<PointF> with tolerance? Let’s say my Equals code is like this
public const float Epsilon = 0.01; //say
public bool Equals(PointF pt1, PointF pt2)
{
return Math.Abs(pt1.X-pt2.X)<Epsilon && Math.Abs(pt1.Y-pt2.Y)<Epsilon;
}
Question: How to implement the correct GetHashCode so that for a dictionary of PointF, I will access the element correctly?
I crack my head a few days but still can’t find a satisfactory solution.
Instead of defining the tolerance by the distance, you could place the points in a grid.
If two points are in the same cell, they’re considered equal and have the same hash code.
Thesis: There is no implementation of
EqualsandGetHashCodethat meets your requirements.Proof: Consider the following three points, A, B, and C:
As per your requirements,
But from (iv) and (v) follows
and thereby
which contradicts (iii) and (vi).
Since
EqualsandGetHashCodecannot return different values for the same arguments, there is no implementation that meets your requirements.q.e.d.