我知道复数比较运算符一般不能定义。这就是python在尝试使用现成的复杂比较时抛出TypeError
异常的原因。我明白为什么会这样(请不要偏离主题,试图解释为什么两个复数不能比较)。在
也就是说,在这个特殊的例子中,我想根据它们的大小来进行复数比较。换句话说,对于z1
和z2
复值,则z1 > z2
当且仅当abs(z1) > abs(z2)
,其中{numpy.abs()
。在
我想出了一个解决方案(至少我想我已经有了)如下:
import numpy as np
class CustomComplex(complex):
def __lt__(self, other):
return np.abs(self) < np.abs(other)
def __le__(self, other):
return np.abs(self) <= np.abs(other)
def __eq__(self, other):
return np.abs(self) == np.abs(other)
def __ne__(self, other):
return np.abs(self) != np.abs(other)
def __gt__(self, other):
return np.abs(self) > np.abs(other)
def __ge__(self, other):
return np.abs(self) >= np.abs(other)
complex = CustomComplex
这似乎有效,但我有几个问题:
complex
数据类型以及numpy.complex
。如何在没有代码重复的情况下优雅地完成这项工作?在
我恐怕要偏离主题了(是的,我已经读了你的帖子了)。好吧,Python允许您尝试用这种方式比较复数,因为您可以单独定义所有运算符,即使我强烈建议您不要像您那样重新定义
__eq__
:您正在说1 == -1
!在问题就在这里,并且会在某个时刻出现在你的面前(或者任何使用你的包的人的脸上):当使用等式和不等式时,普通人(和大多数python代码)会做一些简单的假设,比如}。仅仅因为数学上的原因,这两个假设是不可能同时成立的。在
-1 != 1
,(a <= b) && (b <= a)
意味着{另一个经典假设是
a <= b
相当于-b <= -a
。但是对于你来说,a <= b
相当于-a <= -b
!在话虽如此,我将试着回答你的两个问题:
但不是基于您自己的代码进行的广泛测试:
按照你的要求,我将放弃所有这可能是个坏主意的理由。在
当普通的
abs
接受复数并且速度快得多的时候,不需要使用numpy。在functools
中还有一个方便的total_ordering
,它适用于这种简单的比较,如果您想减少代码(但这可能会比较慢):(这就是您需要的所有代码。)
当正确的参数是普通复数(或任意)数时,它会自动工作:
^{pr2}$但是如果你想使用操作符
<
等等,而不是函数,那就是你能做的最好的了。complex
类型不允许您设置__lt__
,TypeError是硬编码的。在如果要对普通
complex
数字进行这样的比较,则必须定义并使用自己的比较函数,而不是普通运算符。或者只使用abs(a) < abs(b)
,这是清楚的,不是非常冗长。在*内置计时
abs
与numpy.abs
:相关问题 更多 >
编程相关推荐