NumPy: Check element-wise True/False of a given array where signbit is set
NumPy Mathematics: Exercise-36 with Solution
Write a NumPy program to check element-wise True/False of a given array where signbit is set.
Sample array: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array with integer values ranging from -4 to 4
x = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
# Displaying the original array
print("Original array: ")
print(x)
# Calculating sign bit of each element in the array using np.signbit()
r1 = np.signbit(x)
# Comparing if each element is less than zero to determine sign bit as a boolean array
r2 = x < 0
# Verifying if both approaches yield the same result
assert np.array_equiv(r1, r2)
# Displaying the sign bit of each element in the array
print(r1)
Sample Output:
Original array: [-4 -3 -2 -1 0 1 2 3 4] [ True True True True False False False False False]
Explanation:
x = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4]): This code initializes a NumPy array x with 9 integers ranging from -4 to 4.
r1 = np.signbit(x): Here np.signbit(x) function returns a boolean array with the same shape as x, where True corresponds to a negative value and False corresponds to a non-negative value.
r2 = x < 0: Here the expression x < 0 returns a boolean array with the same shape as x, where True corresponds to a negative value and False corresponds to a non-negative value.
assert np.array_equiv(r1, r2): As the above two results are equivalent therefore assert returns true.
Python-Numpy Code Editor:
Next: Write a NumPy program to change the sign of a given array to that of a given array, element-wise.
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://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-36.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics