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

孤人 提交于 2019-12-01 19:32:46

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.

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