Python Division Of Complex Numbers Without Using Built In Types and Operators

前提是你 提交于 2019-12-14 01:17:53

问题


I have to implement a class called ComplexNumbers which is representing a complex number and I'm not allowed to use the built in types for that. I already have overwritten the operators (__add__, __sub__, __mul__, __abs__, __str_ which allows to perform basic operations. But now I'm stuck with overwriting the __div__ operator.

Allowed to use:

I'm using float to represent the imaginary part of the number and float to represent the rel part.

What I have already tried:

  • I looked up how to perform a division of complex numbers (handwritten)
  • I have done an example calculation
  • Thought about how to implement it programatically without any good result

Explanation of how to divide complex numbers:

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

My implementation of multiply:

 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)

回答1:


I think this should suffice:

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__



回答2:


Thanks to the tips of @PatrickHaugh I was able to solve the problem. Here is my solution:

  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)

Calculating the conjugation and than the denominator which has no imaginary part.



来源:https://stackoverflow.com/questions/41144760/python-division-of-complex-numbers-without-using-built-in-types-and-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!