# Numeric comparison anomaly

Jim Meyer jmeyer at pdi.com
Thu Feb 20 23:28:29 CET 2003

```Hello!

On Thu, 2003-02-20 at 13:30, Gary Herron wrote:
> > > From: Piet van Oostrum [mailto:piet at cs.uu.nl]
> > > Sent: Thursday, February 20, 2003 4:56 AM
> > >
> > > >>>>> Gerrit Holl <gerrit at nl.linux.org> (GH) schreef:
> > >
> > > GH> You can use the __cmp__ overloader:
> > >
> > > GH>  21 >>> class A:
> > > GH>  21 ...  def __cmp__(self, other):
> > > GH>  21 ...   return 1
> > > GH>  21 ...
> > > GH>  22 >>> A() > 5
> > > GH> True
> > > GH>  23 >>> A() < 9
> > > GH> False
> > > GH>  24 >>> A() >= 3
> > > GH> True
> > >
> > > >>> inf = A()
> > > >>> inf > inf
> > >
> > > True
> > >
> > > >>> inf == inf
> > >
> > > False

> This is correct of course.  By having __cmp__ return 1 *always*, you
> are saying inf is greater than *anything* else without regard to what
> the other thing is.  (Note that your __cmp__ does not even look at the
> second argument.)  It will never compare equal to anything (__cmp__
> would need to return a zero for that).

While I understand that this is the correct behavior for the above
implementation, I wonder if the implicit question wasn't "Shouldn't
infinity evaluate to be equal to infinity?"

Interestingly, Java considers the cases of both positive and negative
infinity. They are respectively greater than and less than everything
(except themselves); they are equal to themselves only.

Here's a slightly different snippet to break:

class INFINITY:
def __init__(self, type = 1) :
self.sign = cmp(type, 0)
if not self.sign: self.sign = 1
def __cmp__(self, other) :
if isinstance(other, INFINITY) :
return cmp(self.sign, other.sign)
else :
return self.sign

>>> posinf = INFINITY()
>>> neginf = INFINITY(-1)
>>> 1 > neginf
1
>>> 1 < posinf
1
>>> neginf > posinf
0
>>> posinf > neginf
1
>>> posinf > posinf
0
>>> posinf < posinf
0
>>> posinf == posinf
1

You get the idea.

--j, who wonders if 'self.sign = 0' might ever be interesting ...
--
Jim Meyer, Geek at Large                                  jmeyer at pdi.com

```