Skip to main content
1 of 4
Marten
  • 279
  • 2
  • 6

Implementing equality testing and hashing of float attributes without checking the floats with ==

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 implies hash(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?

Marten
  • 279
  • 2
  • 6