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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值