w3resource

NumPy: Find the real and imaginary parts of an array of complex numbers


Real/Imaginary Parts of Complex Array

Write a NumPy program to find the real and imaginary parts of an array of complex numbers

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Calculating square root of a complex number
x = np.sqrt([1 + 0j])

# Calculating square root of another complex number
y = np.sqrt([0 + 1j])

# Printing the original array 'x' and 'y'
print("Original array:x ", x)
print("Original array:y ", y)

# Printing the real part of the array 'x' and 'y'
print("Real part of the array:")
print(x.real)
print(y.real)

# Printing the imaginary part of the array 'x' and 'y'
print("Imaginary part of the array:")
print(x.imag)
print(y.imag) 

Sample Output:

Original array:x  [ 1.+0.j]
Original array:y  [ 0.70710678+0.70710678j]
Real part of the array:
[ 1.]
[ 0.70710678]
Imaginary part of the array:
[ 0.]
[ 0.70710678]

Explanation:

In the above code -

x = np.sqrt([1+0j]): Calculates the square root of the complex number (1+0j) and stores the result in the variable ‘x’.

y = np.sqrt([0+1j]): Calculates the square root of the complex number (0+1j) and stores the result in the variable ‘y’.

print(x.real): Prints the real part of the square root of the complex number (1+0j) stored in ‘x’.

print(y.real): Prints the real part of the square root of the complex number (0+1j) stored in ‘y’.

print(x.imag): Prints the imaginary part of the square root of the complex number (1+0j) stored in ‘x’.

print(y.imag): Prints the imaginary part of the square root of the complex number (0+1j) stored in ‘y’.

Python-Numpy Code Editor: