Python program to add two complex numbers
In this easy tutorial, we will learn how to add two complex numbers in Python.
Complex numbers are a combination of real and imaginary numbers generally written in the form a+bi, where a and b are real and imaginary numbers respectively. In this module, a clear understanding of the addition of two such numbers in python is provided.
Before getting on to the actual code, let us first learn about complex() method in python. This is a built-in function that takes two parameters as inputs and converts it into a complex number; the first input being real and the second imaginary. Furthermore, default values of both, real and imaginary, is 0 when omitted. Syntax of complex() is:
With this in mind, let us start with our topic.
Addition of two complex numbers in Python
Problem statement: Write a python program to add two complex numbers.
Suppose, we have two complex numbers, a1+b1j and a2+b2j. Sum of these two numbers will be,
Now, let us take an example of two numbers, 2+3j & 4+6j. Solving them, we get,
- Accept inputs of two complex numbers from the user using complex() method.
- Add the two numbers.
print("Enter two complex numbers in the form a+bj:") n1 = complex(input()) n2 = complex(input()) print("sum =", n1 + n2)
Here, first, a print statement is displayed with the format in which input should be given by the user. Next, inputs are taken by the user as n1 and n2. Finally, the sum of the two numbers is printed.
Enter two complex numbers in the form a+bj: 2+3j 4+6j sum = (6+9j)
Thus, we have successfully added two complex numbers provided by the user with the easiest possible technique.