问题
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