Search code examples
pythondivisioncomplex-numbersbuilt-in-types

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


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)

Solution

  • 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__