gpt4 book ai didi

python - 如何在Python中构建复数类?

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:24 24 4
gpt4 key购买 nike

首先,我知道scipy中有复数的数据结构。我正在阅读一本计算物理教科书,这是问题之一。到目前为止,这就是我所得到的:

class complex:
def __init__(self,x,y):
self.re=x
self.im=y
def __add__(self, other):
return complex(self.re+other.re, self.im+other.im)
def __sub__(self, other):
return complex(self.re-other.re, self.im-other.im)
def __mul__(self, other):
return complex(self.re*other.re - self.im*other.im,
self.re*other.im + self.im*other.re)
def __repr__(self):
return '(%f , %f)' %(self.re, self.im)

但是我应该如何在我创建的类中实现除法、复共轭、模数和相位?

谢谢

最佳答案

除法应使用 __div__ 实现,模数应使用 __abs__ 实现。您必须为复杂的共轭和相位选择自己的方法名称。例如,

def conj(self):
return complex(self.re, - self.im)

(使用 z.conj() 调用)。请注意,您将无法为您的类定义新的 Python 语法:例如,您无法使 z* 工作。如果您愿意,您还应该使用 __rmul____pow__ 定义右乘。并且不要忘记一元减号,__neg__。但并非所有其他双下划线运算符方法都适合用复数实现。有a list in the docs

关于python - 如何在Python中构建复数类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com