Complex Data Type
Understanding Complex Numbers
In Python, the complex data type represents complex numbers. A complex number is a number that can be expressed in the form a + bj, where:
- a is the real part
- b is the imaginary part
- j is the imaginary unit, defined as the square root of -1
Creating Complex Numbers
To create a complex number, you can use the following syntax:
Python
z = complex(real, imag)
where real and imag are the real and imaginary parts, respectively.
Alternatively, you can use the j suffix:
Python
z = 3 + 2j
Example
Python
# Creating complex numbers
z1 = complex(3, 2)
z2 = 4 - 5j
print(z1) # Output: (3+2j)
print(z2) # 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:
Python
z = 3 + 2j
real_part = z.real
imag_part = z.imag
print(real_part) # Output: 3.0
print(imag_part) # Output: 2.0
Complex Arithmetic
Python supports arithmetic operations on complex numbers:
Python
z1 = 3 + 2j
z2 = 1 - 4j
sum_complex = z1 + z2
difference = z1 - z2
product = z1 * z2
quotient = z1 / z2
print(sum_complex) # Output: (4-2j)
print(difference) # Output: (2+6j)
print(product) # Output: (19+10j)
print(quotient) # Output: (-0.2-0.8j)
Built-in Functions
While there are no specific methods for the complex data type, Python provides some built-in functions that can be used with complex numbers:
- abs(z): Returns the magnitude (absolute value) of the complex number z.
- conjugate(z): Returns the complex conjugate of z.
Example
Python
z = 3 + 4j
magnitude = abs(z)
conjugate = z.conjugate()
print(magnitude) # Output: 5.0
print(conjugate) # Output: (3-4j)
Complex numbers are essential in various fields, including mathematics, physics, and engineering. Python's support for complex numbers makes it a versatile language for these domains.