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’.


For more Practice: Solve these Related Problems:

  • Extract the real and imaginary parts of a complex array using np.real and np.imag.
  • Swap the real and imaginary parts of a complex array and reconstruct the complex numbers.
  • Create a function that returns both the magnitude and phase of each element in a complex array.
  • Validate the extraction by performing arithmetic on the separate parts and comparing with the original array.

Go to:


PREV : Celsius to Fahrenheit Conversion
NEXT : Array Elements Count & Memory Usage


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.