w3resource

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


36. Check Signbit Element-wise

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.


For more Practice: Solve these Related Problems:

  • Implement a function that returns a boolean array indicating whether the sign bit is set for each element using np.signbit.
  • Test the function on an array containing both negative and positive values to verify correct True/False output.
  • Create a solution that applies np.signbit to a multi-dimensional array and ensures consistency in dimensions.
  • Compare the np.signbit output with a simple comparison (x < 0) for validation on various inputs.

Go to:


PREV : Compute log1p (Natural Logarithm of 1 + x)
NEXT : Copy Sign from One Array to Another

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.