天天看點

python中複數表達形式_在Python中實作複數比較?

按照你的要求,我将放棄所有這可能是個壞主意的理由。在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