user1142217
user1142217

Reputation:

Comparison throws an error on complex inputs, but not on numpy.complex64?

The complex numbers are not an ordered field, so this makes sense to me:

$ python3 -c 'print(1.0<1.0+1.0j)'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: '<' not supported between instances of 'float' and 'complex'

It generates an error, as it should. I get identical output with 1.0<numpy.complex(1.0+1.0j)', which also makes sense. But then I have the following:

$ python3 -c 'import numpy; print(1.0<numpy.complex64(1.0+1.0j))'
True
$ python3 -c 'import numpy; print(1.0<numpy.complex64(1.0-1.0j))'
False

Is this simply a bug in numpy's implementation of complex64? Is this behavior intentionally left undefined for efficiency? I tried googling on seemingly relevant search terms like "comparison numpy.complex64," but didn't find anything. It doesn't seem like it's comparing magnitudes, since then both comparisons would have been true. Possibly it's doing a lexicographic comparison on real and imaginary parts, which seems useless but I guess would be OK if it was the documented behavior for some reason.

If this behavior was not intentionally introduced and documented anywhere, then it seems to me that it should be changed, since it introduces behavior that is probably not expected in cases where you don't realize that your number has a very small imaginary part due to numerical error. (I came across this because I was getting x.real>x half the time, because x had a small imaginary part with a random sign.)

Upvotes: 1

Views: 151

Answers (1)

mattlangford
mattlangford

Reputation: 1260

After looking around quite a bit and also not finding any documented behavior I'm in the same boat as you.

I would guess that doing the comparison results in the floating point type being converted into a complex number (something like 1.0 + 0.0j) and then the comparison is doing a lexicographic comparison like you suggested. Since 0j is not less than -1j, the result if False.

You're right that numerical errors can crop up and cause unexpected results, but that's the case all over the place with small differences in floating point numbers.

Upvotes: 1

Related Questions