按照你的要求,我将放弃所有这可能是个坏主意的理由。在Is this the way to go or is there a better alternative?
当普通的abs接受复数并且速度快得多的时候,不需要使用numpy。在functools中还有一个方便的total_ordering,它适用于这种简单的比较,如果您想减少代码(但这可能会比较慢):from functools import total_ordering
@total_ordering
class CustomComplex(complex):
def __eq__(self, other):
return abs(self) == abs(other)
def __lt__(self, other):
return abs(self) < abs(other)
(这就是您需要的所有代码。)I would like my package to transparently work with the built-in complex data type as well as numpy.complex. How can this be done elegantly, without code duplication?
当正确的参数是普通复数(或任意)数时,它会自动工作:
^{pr2}$
但是如果你想使用操作符
如果要对普通complex数字进行这样的比较,则必须定义并使用自己的比较函数,而不是普通运算符。或者只使用abs(a) < abs(b),这是清楚的,不是非常冗长。在
*内置计时abs与numpy.abs:>>> timeit.timeit('abs(7+6j)')
0.10257387161254883
>>> timeit.timeit('np.abs(7+6j)', 'import numpy as np')
1.6638610363006592