Python Program to Subtract Two Complex Numbers

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

Getting Started

Complex numbers are number that can be represented in the form of x+yj where x and y are real numbers. For example, 2+1j, 4-3j etc.

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

Now, we will learn about how to subtract two complex numbers using python programming language. For example,

If a = 13+40j and b = 5+12j, then a – b = 8+28j

We can perform above task in multiple ways –

Simple Approach

We use subtraction operator (i.e. operator) to subtract two complex numbers. For example,

 
a = 12+6j
b = 2+3j
result = a - b
print("Result =", result)

Output:

 
Result = (10+3j)

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: 
12+8j
Enter second complex number: 
5+8j
Result = (7+0j)

Using Lambda

lambda and + operator can also be used to subtract two complex numbers. For example,

 
if __name__ == "__main__" :
    num1 = 15+86j
    num2 = 14+32j
     
    # Subtract two complex numbers
    subtract_twoNum = lambda num1, num2 : num1 - num2
    print("Result =", subtract_twoNum(num1, num2))

Output:

 
Result = (1+54j)

Using Function

Logic to subtract two complex numbers can also be written inside python function as well. For example,

 
def findSubtract(a, b):
    return a - b
 
print("Result =", findSubtract(20+2j, 10+12j))

Output:

 
Result = (10-10j)

Using user defined Complex number using Class

We can define our own format of complex number using class as well. If we have done so and we need to write logic to subtract two complex numbers, we can do so as shown below –

 
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 subtract(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("Subtract = ")
c3 = ComplexNumber()
c3.subtract(c1, c2)
c3.display()

Output:

 
First complex number: 
Enter Real part: 
12
Enter Imaginary part: 
4
Second complex number: 
Enter Real part: 
2
Enter Imaginary part: 
4
Subtract = 
10+0j

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

Reference: Official Doc

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

Leave a Reply