In Python, the complex data type is used to represent complex numbers. Complex numbers are a combination of a real part and an imaginary part, where the imaginary part is denoted by the letter ‘j’ (or ‘J’).
Creating Complex Numbers
To create a complex number in Python, you can use the complex() function or by directly assigning values to the real and imaginary parts.
Syntax:
complex(real, imaginary)
real + imaginary * j
Example:
# Using complex()
c1 = complex(2, 3)
print(c1) # Output: (2+3j)
# Direct assignment
c2 = 4 + 5j
print(c2) # Output: (4+5j)
Accessing Real and Imaginary Parts
You can access the real and imaginary parts of a complex number using the .real and .imag attributes respectively.
Example:
c = complex(3, -4)
print(c.real) # Output: 3
print(c.imag) # Output: -4
Performing Operations on Complex Numbers
The complex data type supports various arithmetic operations such as addition, subtraction, multiplication, division, etc.
Addition and Subtraction:
In Python, adding or subtracting two complex numbers is similar to adding or subtracting real numbers. The real parts are added/subtracted separately, and the same is done for the imaginary parts.
Example:
c1 = complex(2, 3)
c2 = complex(4, 5)
sum_result = c1 + c2
diff_result = c1 - c2
print(sum_result) # Output: (6+8j)
print(diff_result) # Output: (-2-2j)
Multiplication:
To multiply complex numbers, you can use the ‘*’ operator. The multiplication follows the distributive property.
mul_result = c1 * c2
print(mul_result) # Output: (-7+22j)
Division:
The division of complex numbers can be performed using the ‘/’ operator. The division is done by multiplying both the numerator and denominator by the conjugate of the denominator.
Example:
Conclusion
In Python, complex numbers can be easily created using the complex() function or direct assignment. They support various arithmetic operations like addition, subtraction, multiplication, and division. By understanding how to work with complex numbers in Python, you can perform calculations involving real and imaginary quantities with ease.