Answer to Question #302668 in Python for Santosh

Question #302668

Write a python program to design a class representing complex numbers and having the functionality of performing addition & multiplication of two complex numbers using operator overloading

1
Expert's answer
2022-02-25T07:52:40-0500
class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary


    def __add__(self, num):
        return Complex(self.real + num.real, self.imaginary + num.imaginary)


    def __mul__(self, num):
        x = self.real
        y = self.imaginary
        u = num.real
        v = num.imaginary
        real = x * u - y * v
        img = x * v + y * u
        return Complex(real, img)


    def __str__(self):
        sign = '+' if self.imaginary >= 0 else '-'
        result = "%.2f %s %.2fi" % (self.real, sign, abs(self.imaginary))
        return result


# put this code in a main method


Inp = (str(input("Enter the first  complex No. (Real and Imag followed by space: "))).split(" ")
C = [0]*2
C[0] = float(Inp[0])
C[1] = float(Inp[1])
Inp = (str(input("Enter the second complex No. (Real and Imag followed by space: "))).split(" ")
D = [0]*2
D[0] = float(Inp[0])
D[1] = float(Inp[1])


x = Complex(*C)
y = Complex(*D)
print("Result of Complex Number Addition      :",x+y)
print("Result of Complex Number Multiplication:",x*y)


Python Output:

Enter the first complex No. (Real and Imag followed by space: 3 4

Enter the second complex No. (Real and Imag followed by space: 5 3

Result of Complex Number Addition   : 8.00 + 7.00i

Result of Complex Number Multiplication: 3.00 + 29.00i

>>> 


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS