Let's say we have the following python class (the problem exists in java just the same with equals and hashCode)
class Temperature:
def __init__(self, degrees):
self.degrees = degrees
where degrees is the temperature in Kelvin as a float. Now, I would like to implement equality testing and hashing for Temperature in a way that
- compares floats up to an epsilon difference instead of direct equality testing,
- and honors the contract that
a == bimplieshash(a) == hash(b).
def __eq__(self, other):
return abs(self.degrees - other.degrees) < EPSILON
def __hash__(self):
return # What goes here?
The python documentation talks a bit about hashing numbers to ensure that hash(2) == hash(2.0) but this is not quite the same problem.
Am I even on the right track? And if so, what is the standard way to implement hashing in this situation?