Equality and Equivalence

2010-06-09, Comments

Kevin Bacon mugshot

If A <= B and B <= A then A and B must be equal, right?

Wrong, actually.

We could rank actors according to their Bacon number, for example. Hugh Grant and Daniel Day-Lewis both have a Bacon number of 2, but that doesn’t make them equal!

I think most programmers get the distinction between ordering and equality, but it’s easy to forget.

Part of the problem is the less-than-or-equal-to and greater-than-or-equal-to operators both mention equal. The standard programming representation of these operators includes a single equals symbol, whil the representation of equality has two equals symbols. Symbolically we might assume:

<=  >=  == 


Another part of the problem is that we tend to think of numbers as archetypal objects: when in doubt, do as the ints do. For integers, it’s true, equality and equivalence are the same. The same is true of real numbers, but what about their floating point representations? A NaN doesn’t even equal itself. Complex numbers have no standard comparison operators.

>>> 3+4j == 4j+3
>>> 3+4j <= 4j+3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers

To avoid trouble, remember that the equal in less-than-or-equal-to should really be equivalent.

Oh, and please don’t confuse equality with assignment.