See this question for some background. My main problem on that question was solved, and it was suggested that I ask another one for a second problem I'm having:
print cubic(1, 2, 3, 4) # Correct solution: about -1.65
...
if x > 0:
TypeError: no ordering relation is defined for complex numbers
print cubic(1, -3, -3, -1) # Correct solution: about 3.8473
if x > 0:
TypeError: no ordering relation is defined for complex numbers
Cubic equations with one real root and two complex roots are receiving an error, even though I am using the cmath module and have defined the cube root function to handle complex numbers. Why is this?
Python's error messages are pretty good, as these things go: unlike some languages I could mention, they don't feel like random collections of letters. So when Python complains of the comparison
if x > 0:
that
TypeError: no ordering relation is defined for complex numbers
you should take it at its word: you're trying to compare a complex number x
to see whether or not it's greater than zero, and Python doesn't know how to order complex numbers. Is 2j > 0
? Is -2j > 0
? Etc. In the face of ambiguity, refuse the temptation to guess.
Now, in your particular case, you've already branched on whether or not x.imag != 0
, so you know that x.imag == 0
when you're testing x
and you can simply take the real part, IIUC:
>>> x = 3+0j
>>> type(x)
<type 'complex'>
>>> x > 0
Traceback (most recent call last):
File "<ipython-input-9-36cf1355a74b>", line 1, in <module>
x > 0
TypeError: no ordering relation is defined for complex numbers
>>> x.real > 0
True
It is not clear from your example code what x
is, but it seems it must be a complex number. Sometimes, when using complex numerical methods, an approximate solution will come up as a complex number even though the exact solution is supposed to be real.
Complex numbers have no natural ordering, so an inequality x > 0
makes no sense if x
is complex. That's what the type error is about.
来源:https://stackoverflow.com/questions/16291902/why-am-i-receiving-a-no-ordering-relation-defined-for-complex-numbers-error