Complex numbers are used in many fields like engineering, physics, and mathematics. Despite this, many programming languages do not handle complex numbers straight out of the box.
Luckily, Python does! In this tutorial, we’ll be learning how to add complex numbers in Python.
Step 1: Understanding Complex Numbers in Python
In Python, complex numbers are represented in the form of x + yj, where x represents the real part and y represents the imaginary part. The ‘j’ is like ‘i’ in mathematics, denoting the square root of -1. Python provides a built-in complex data type for handling these numbers.
Step 2: Writing Addition Code
To add complex numbers, we just need to add real parts together and imaginary parts together separately. Here’s the code:
1 2 3 4 |
cn1 = complex(3, 4) cn2 = complex(1, 2) sum = cn1 + cn2 print("The sum is :", sum) |
In the script above, we created two complex numbers cn1 and cn2, and added them together. We stored the result in the sum variable and printed out the result.
Step 3: Understanding the Output
The output of our script will be:
The sum is : (4+6j)
The real parts (3 and 1) have been added together to form 4, and the imaginary parts (4 and 2) have been added together to form 6.
Step 4: Handling Input from User
What if you want to allow the user to input their own complex numbers? Let’s refine our code to accept input from the user:
1 2 3 4 5 6 7 8 9 10 11 |
x1 = float(input("Enter the real part of first number: ")) y1 = float(input("Enter the imaginary part of first number: ")) x2 = float(input("Enter the real part of second number: ")) y2 = float(input("Enter the imaginary part of second number: ")) cn1 = complex(x1, y1) cn2 = complex(x2, y2) sum = cn1 + cn2 print("The sum is :", sum) |
Full Code
Here’s the full Python code you can use to add complex numbers, either hardcoded or entered by a user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Hardcoded complex numbers cn1 = complex(3, 4) cn2 = complex(1, 2) # Calculating and printing their sum sum = cn1 + cn2 print("The sum is :", sum) # User-defined complex numbers x1 = float(input("Enter the real part of first number: ")) y1 = float(input("Enter the imaginary part of first number: ")) x2 = float(input("Enter the real part of second number: ")) y2 = float(input("Enter the imaginary part of second number: ")) cn1 = complex(x1, y1) cn2 = complex(x2, y2) # Calculating and printing their sum sum = cn1 + cn2 print("The sum is :", sum) |
Conclusion
Adding complex numbers in Python is straightforward thanks to Python’s built-in complex data type. You can either specify your own complex numbers within the script or allow the user to input their own. Now you should be able to use Python to make calculations using complex numbers.