Complex numbers 2.0

Report a typo

In this topic, we've defined the class ComplexNumber and several magic methods for this class. However, it makes sense to define a couple of other methods so that we can use this class to its full potential.

We need methods for subtraction and division.

Subtraction

If we have 2 complex numbers x=a+bix = a + bi and y=c+diy = c + di , then xyx - y will equal (ac)+(bd)i(a - c) + (b - d)i.

Division

For division, we need to calculate the reciprocal of a complex number. If x=a+bix = a + bi, then 1x=aa2+b2ba2+b2i{1 \over x} = {a \over a^2 + b^2} - {b \over a^2 + b^2}i.

xy{x \over y} can then be represented as x1yx * {1 \over y}.

Write a program in Python 3
class ComplexNumber:
def __init__(self, real_part, im_part):
self.real_part = real_part
self.im_part = im_part

def __add__(self, other):
real = self.real_part + other.real_part
imaginary = self.im_part + other.im_part
return ComplexNumber(real, imaginary)

def __mul__(self, other):
real = self.real_part * other.real_part - self.im_part * other.im_part
imaginary = self.real_part * other.im_part + other.real_part * self.im_part
return ComplexNumber(real, imaginary)

def __eq__(self, other):
return ((self.real_part == other.real_part) and
(self.im_part == other.im_part))

def __str__(self):
if self.im_part < 0:
sign = "-"
else:
sign = "+"
string = "{} {} {}i".format(self.real_part, sign, abs(self.im_part))
return string

# define the rest of the methods here
___

Create a free account to access the full topic