In this article, we will learn about python program to multiply two complex numbers with examples.
Getting Started
Complex numbers are number that can be represented as –
a+bj, Where, a and b are real numbers
For example,
13+4j, 5-14j, 2.3+4j etc.
We have already covered how to
Now, we will learn about how to multiply two complex numbers in python. For example,
If a = 30+4j and b = 15+2j, then a x b = 442+120j
We have to do such multiplication of complex numbers using python programming.
We can achieve above task in multiple ways –
- Simple Approach
- Using User Input
- Using Lambda
- Using Function
- Using user defined Complex number using Class
Simple Approach
Multiplication operator (i.e. * operator) can be used to multiply two complex numbers. For example,
a = 30+4j
b = 15+2j
result = a * b
print("Result =", result)
Output:
Result = (442+120j)
Using User Input
In above example, two complex numbers were hardcoded values. We can take those complex numbers as input from user as well. For example,
a = complex(input("Enter first complex number: "))
b = complex(input("Enter second complex number: "))
result = a * b
print("Result =", result)
Output:
Enter first complex number: 10+2j Enter second complex number: 1+4j Result = (2+42j)
Using Lambda
We can also use lambda and * operator to multiply two complex numbers. For example,
if __name__ == "__main__" :
num1 = 15+86j
num2 = 14+32j
# Multiply two complex numbers
multiply_twoNum = lambda num1, num2 : num1 * num2
print("Result =", multiply_twoNum(num1, num2))
Output:
Result = (-2542+1684j)
Using Function
We can write logic to multiply two complex numbers inside python function as well. For example,
def multiplyComplex(a, b):
return a * b
print("Result =", multiplyComplex(20+2j, 10+12j))
Output:
Result = (176+260j)
Using user defined Complex number using Class
Writing logic to multiply two complex numbers is bit tricky when we have user defined complex number using class. For example,
class ComplexNumber():
def init(self):
self.real = int(input("Enter Real part: "))
self.imaginary = int(input("Enter Imaginary part: "))
def display(self):
sign = "+" if(self.imaginary >= 0) else ""
print(self.real, sign, self.imaginary, "j", sep="")
def multiply(self, c1, c2):
res = complex(c1.real, c1.imaginary) * complex(c1.real, c1.imaginary)
self.real = res.real
self.imaginary = res.imag
print("First complex number: ")
c1 = ComplexNumber()
c1.init()
print("Second complex number: ")
c2 = ComplexNumber()
c2.init()
print("Result = ")
c3 = ComplexNumber()
c3.multiply(c1, c2)
c3.display()
Output:
First complex number: Enter Real part: 10 Enter Imaginary part: 10 Second complex number: Enter Real part: 20 Enter Imaginary part: 20 Result = 0.0+200.0j
That’s how we can write python program to multiply two complex numbers with examples.
Reference: Official Doc
Learn about more python examples at – https://tutorialwing.com/python-tutorial/