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