不使用内置类型和运算符的Python复数除法

2024-10-03 19:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须实现一个名为ComplexNumbers的类,它代表一个复数,不允许使用内置类型。 我已经重写了允许执行基本操作的运算符(__add____sub____mul____abs____str_)的运算符。 但是现在我不得不重写__div__运算符。在

允许使用:

我使用float来表示数字的虚部,float来表示rel部分。在

我已经试过了:

  • 我查了如何对复数进行除法(手写)
  • 我做了一个算例
  • 在没有任何好结果的情况下,思考如何用程序实现它

复数除法说明:

http://www.mathwarehouse.com/algebra/complex-number/divide/how-to-divide-complex-numbers.php

我的乘法实现:

 def __mul__(self, other):
        real = (self.re * other.re - self.im * other.im)
        imag = (self.re * other.im + other.re * self.im)
        return ComplexNumber(real, imag)

Tags: selfre运算符代表floatreal内置复数
2条回答

我认为这就足够了:

def conjugate(self):
    # return a - ib

def __truediv__(self, other):
    other_into_conjugate = other * other.conjugate()
    new_numerator = self * other.conjugate()
    # other_into_conjugate will be a real number
    # say, x. If a and b are the new real and imaginary
    # parts of the new_numerator, return (a/x) + i(b/x)

__floordiv__ = __truediv__

多亏了@PatrickHaugh的建议,我才得以解决这个问题。我的解决方案是:

  def __div__(self, other):
        conjugation = ComplexNumber(other.re, -other.im)
        denominatorRes = other * conjugation
        # denominator has only real part
        denominator = denominatorRes.re
        nominator = self * conjugation
        return ComplexNumber(nominator.re/denominator, nominator.im/denominator)

计算共轭和比分母没有虚部。在

相关问题 更多 >