Why am I receiving a “no ordering relation defined for complex numbers” error?

梦想与她 提交于 2019-12-31 00:45:09

问题


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?


回答1:


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



回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!