Python Program to Add Two Complex Numbers

In this article, we will learn about python program to add two complex numbers with examples

Getting Started

Complex numbers are number that are represented as a+bj where a and b are real numbers. For example, 3+4j, 5-4j, 2.1+4j etc.

We have already covered how to add two real numbers in python.

Now, we will learn about how to add two complex numbers in python. For example,

If a = 3+4j and b = 5+2j, then a + b = 8+6j

We have to do above addition of complex numbers using python programming.

We can achieve above task in multiple ways –

Simple Approach

We use addition operator (i.e. + operator) to add two complex number. For example,

 
a = 4+2j
b = 6+3j
sum = a + b
print("Sum =", sum)

Output:

 
Sum = (10+5j)

In above program, we added two complex numbers, a and b, using + operator.

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: "))
sum = a + b
print("Sum =", sum)

Output:

 
Enter first complex number: 
3+2j
Enter second complex number: 
5+1j
Sum = (8+3j)

Using Lambda

We can also use lambda and + operator to add two complex numbers. For example,

 
if __name__ == "__main__" :
    num1 = 5+6j
    num2 = 4+2j
     
    # Adding two complex numbers
    sum_twoNum = lambda num1, num2 : num1 + num2
    print("Sum =", sum_twoNum(num1, num2))

Output:

 
Sum = (9+8j)

Using Function

We can write logic to add two complex numbers inside python function as well. For example,

 
def findSum(a, b):
    return a + b
 
print("Sum =", findSum(10+12j, 20+2j))

Output:

 
Sum = (30+14j)

Using user defined Complex number using Class

We can also define complex number using class. This is used defined complex number wrapped inside class. Similarly, we also handle logic to add two complex numbers inside a function in 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 sum(self, c1, c2):
        self.real = c1.real + c2.real
        self.imaginary = c1.imaginary + c2.imaginary


print("First complex number: ")
c1 = ComplexNumber()
c1.init()

print("Second complex number: ")
c2 = ComplexNumber()
c2.init()

print("Sum = ")
c3 = ComplexNumber()
c3.sum(c1, c2)
c3.display()

Output:

 
First complex number: 
Enter Real part: 
4
Enter Imaginary part: 
2
Second complex number: 
Enter Real part: 
7
Enter Imaginary part: 
1
Sum = 
11+3j

That’s how we can write python program to add two complex numbers with examples.

Reference: Official Doc

Learn about more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply