[Tutor] Complex numbers can't be ordered algebraically

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Apr 21 14:21:02 EDT 2004



On 20 Apr 2004, Lloyd Kvam wrote:

> Obviously, I was not terribly clear.  I DID mean to point out that
> complex numbers were NOT ordered.  I was trying to offer the example of
> complex numbers as keys or values in a dictionary and not having a
> natural default ordering.


Hi Lloyd,

You were perfectly clear --- I did know that you knew that complex numbers
weren't ordered.  Hmmm... but I didn't make that clear in my own message
on Tutor.  My apologies!  I meant to address my response to folks on the
list.


I wanted to show the details why you mentioned complex numbers. For people
who are not too familiar with them, it seems very counterintuitive to say
that '<' doesn't apply to complex numbers.  Aren't they're "numbers"?
And in our intuitive experience, numbers can be ordered.


It's something to keep in the back of one's mind, because it's the reason
why sort()ing a list of complex numbers won't work without manual
intervention.

###
>>> import random
>>> def makeRandomComplex():
...     return random.randrange(0, 10) + random.randrange(0, 10) * 1j
...
>>> numbers = [makeRandomComplex() for x in range(5)]
>>> numbers
[(6+3j), (4+4j), (7+4j), (6+4j), (2+0j)]
>>>
>>> numbers.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
>>>
>>>
>>> def mag(c):
...     return (c.imag **2 + c.real ** 2)**(0.5)
...
>>> def cmpByMag(a, b):
...     return cmp(mag(a), mag(b))
...
>>> numbers.sort(cmpByMag)
>>> numbers
[(2+0j), (4+4j), (6+3j), (6+4j), (7+4j)]
###


Hope this helps!




More information about the Tutor mailing list