NumPy: Find the real and imaginary parts of an array of complex numbers
NumPy: Array Object Exercise-15 with Solution
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:
Previous: Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees and vice versa. Values are stored into a NumPy array.
Next: Write a NumPy program to find the number of elements of an array, length of one array element in bytes and total bytes consumed by the elements
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics