I know that comparison operators with complex numbers can't be defined in general. That is why python throws a TypeError
exception when trying to use out-of-the-box complex comparison. I understand why this is the case (please don't go off topic trying to explain why two complex numbers can't be compared).
That said, in this particular case I would like to implement complex number comparison based on their magnitudes. In other words, for z1
and z2
complex values, then z1 > z2
if-and-only-if abs(z1) > abs(z2)
, where abs()
implements complex number magnitude, as in numpy.abs()
.
I have come up with a solution (at least I think I have) as follows:
import numpy as np
class CustomComplex(complex):
def __lt__(self, other):
return np.abs(self) < np.abs(other)
def __le__(self, other):
return np.abs(self) <= np.abs(other)
def __eq__(self, other):
return np.abs(self) == np.abs(other)
def __ne__(self, other):
return np.abs(self) != np.abs(other)
def __gt__(self, other):
return np.abs(self) > np.abs(other)
def __ge__(self, other):
return np.abs(self) >= np.abs(other)
complex = CustomComplex
This seems to work, but I have a few questions:
- Is this the way to go or is there a better alternative?
- I would like my package to transparently work with the built-in
complex
data type as well asnumpy.complex
. How can this be done elegantly, without code duplication?