See 这个问题一些背景。我在该问题上的主要问题已解决,建议我向另一个问题询问我遇到的第二个问题:
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
即使我使用 cmath 模块并定义了立方根函数来处理复数,具有一个实数根和两个复数根的三次方程也会收到错误。为什么是这样?
Python 的错误消息非常好,正如这些事情一样:与我提到的某些语言不同,它们不像字母的随机集合。所以当Python抱怨比较时
if x > 0:
that
TypeError: no ordering relation is defined for complex numbers
你应该相信它的话:你正在尝试比较一个复数x
查看它是否大于零,而 Python 不知道如何对复数进行排序。是2j > 0
? Is -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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)