为什么我会收到“没有为复数定义的无序关系"?错误? [英] Why am I receiving a "no ordering relation defined for complex numbers" error?
问题描述
有关某些问题,请参见此问题背景.我在该问题上遇到的主要问题已解决,建议我再问一个我遇到的第二个问题:
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
即使我使用cmath模块并定义了立方根函数来处理复数,具有一个实根和两个复数根的三次方程式也会收到错误.为什么会这样?
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的错误消息非常好,因为这些原因:与我能提到的某些语言不同,它们不像字母的随机集合.因此,当Python抱怨比较时
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:
那个
TypeError: no ordering relation is defined for complex numbers
您应该按其字面意思:您正在尝试比较一个复数x
以查看它是否大于零,而Python不知道如何对复数进行排序.是2j > 0
吗?是-2j > 0
吗?等等.面对模棱两可的情况,拒绝猜测的诱惑.
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.
现在,在您的特殊情况下,您已经确定了x.imag != 0
是否存在,因此您在测试x
时就知道x.imag == 0
,您可以简单地使用IIUC的真实部分:
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屋!