NumPy imag()

The numpy.imag() function extracts the imaginary part of a complex number or a NumPy array containing complex numbers. If the input contains only real numbers, the function returns zeros.

Syntax

</>
Copy
numpy.imag(val)

Parameters

ParameterTypeDescription
valarray_likeInput array or scalar. It can be real or complex.

Return Value

Return TypeDescription
ndarray or scalarThe imaginary part of the input. If the input is real, it returns zero with the same data type.

Examples

1. Extracting the Imaginary Part of a Complex Number

Here, we extract the imaginary part of a single complex number.

</>
Copy
import numpy as np

# Define a complex number
complex_number = 3 + 4j

# Extract the imaginary part
imaginary_part = np.imag(complex_number)

# Print the result
print("Imaginary part:", imaginary_part)

Output:

Imaginary part: 4.0

2. Extracting Imaginary Parts from an Array of Complex Numbers

We apply numpy.imag() to an array of complex numbers.

</>
Copy
import numpy as np

# Define an array of complex numbers
complex_array = np.array([1+2j, 3-4j, 5+6j])

# Extract the imaginary parts
imaginary_parts = np.imag(complex_array)

# Print the results
print("Complex numbers:", complex_array)
print("Imaginary parts:", imaginary_parts)

Output:

Complex numbers: [1.+2.j 3.-4.j 5.+6.j]
Imaginary parts: [ 2. -4.  6.]

3. Handling a Mixed Array of Real and Complex Numbers

We use numpy.imag() on an array containing both real and complex numbers.

</>
Copy
import numpy as np

# Define an array with real and complex numbers
mixed_array = np.array([4, 2+3j, 7, 1-1j])

# Extract imaginary parts
imaginary_values = np.imag(mixed_array)

# Print the results
print("Original array:", mixed_array)
print("Imaginary parts:", imaginary_values)

Output:

Original array: [4.+0.j 2.+3.j 7.+0.j 1.-1.j]
Imaginary parts: [ 0.  3.  0. -1.]

4. Extracting Imaginary Parts from a 2D Complex Array

We demonstrate how numpy.imag() works on a multi-dimensional array.

</>
Copy
import numpy as np

# Define a 2D complex array
complex_matrix = np.array([[1+2j, 3+4j], [5-6j, 7+8j]])

# Extract the imaginary parts
imaginary_matrix = np.imag(complex_matrix)

# Print the results
print("Original matrix:\n", complex_matrix)
print("Imaginary part matrix:\n", imaginary_matrix)

Output:

Original matrix:
 [[1.+2.j 3.+4.j]
 [5.-6.j 7.+8.j]]
Imaginary part matrix:
 [[ 2.  4.]
 [-6.  8.]]