w3resource

NumPy: Check element-wise True/False of a given array where signbit is set


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: