【发布时间】:2020-03-06 21:25:03
【问题描述】:
我目前正在为 here 等复数实现自己的类。多亏了这篇文章,我设法做到了两个复数之间的划分。
但我仍然遇到一个问题:我知道4 / (42i + 4) 和(42i + 4) / 4 不一样,但就我而言,我会得到相同的结果。这是因为在这种情况下程序会将数字单独作为整数,并且它无法将整数除以我的 Complex 对象。
我知道我需要创建一个 __rdiv__ 方法来处理这个问题。 我已经为其他基本操作(__add__、__sub__、__mul__)这样做了:
class Complex(object):
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real,
self.imag + other.imag)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
print(self, other)
return Complex(self.real - other.real,
self.imag - other.imag)
def __rsub__(self, other):
return self.__sub__(other)
def __mul__(self, other):
# print(self, other)
return Complex(self.real*other.real - self.imag*other.imag,
self.imag*other.real + self.real*other.imag)
def __rmul__(self, other):
return self.__mul__(other)
但是我不能对除法使用相同的逻辑。也许数学应该有所不同,但我无法理解它。有人可以帮我吗?非常感谢
这是我的 __div__ :
def __div__(self, other):
conjugation = Complex(other.real, -other.imag)
denominatorRes = other * conjugation
denominator = float(denominatorRes.real)
nominator = self * conjugation
try:
return Complex(nominator.real/denominator, nominator.imag/denominator)
except ZeroDivisionError as e:
print e
return None
【问题讨论】:
标签: python class methods division complex-numbers