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 == b
implieshash(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?
Update: Now I understand that this type of equality testing for floats eliminates the transitivity of ==
and equals
. But how does that go together with the "common knowledge" that floats should not be compared directly? If you implement an equality operator by comparing floats, static analysis tools will complain. Are they right to do so?
kelvin
?