为什么我收到"没有为复数定义的排序关系"错误?

4 python math cubic

有些背景,请参阅此问题.我在这个问题上遇到的主要问题已经解决了,有人建议我再向另一个人提出我遇到的第二个问题:

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
Run Code Online (Sandbox Code Playgroud)

具有一个实根和两个复根的三次方程式正在接收错误,即使我使用了cmath模块并定义了多维数据集根函数来处理复数.为什么是这样?

DSM*_*DSM 10

Python的错误信息非常好,因为这些事情发生了:与我提到的某些语言不同,它们不像随机的字母集合.所以当Python抱怨比较时

if x > 0:
Run Code Online (Sandbox Code Playgroud)

TypeError: no ordering relation is defined for complex numbers
Run Code Online (Sandbox Code Playgroud)

你应该明白这一点:你试图比较一个复数x,看它是否大于零,而且Python不知道如何订购复数.是2j > 0吗?是-2j > 0吗?等等.面对模棱两可,拒绝猜测的诱惑.

现在,在你的特定情况下,你已经分支了x.imag != 0,所以你知道,x.imag == 0当你进行测试时x,你可以简单地选择真正的部分,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
Run Code Online (Sandbox Code Playgroud)