What is right_shift() in Numpy?
Overview
The right_shift() is a NumPy function used to shift the bits of an integer to the right. It can take either a number or Numpy array as an argument to right shift the bits.
Syntax
numpy.right_shift(x1,x2,out=None,where=True,**kwargs)
Parameters
It takes the following argument values.
x1: It is an array or integer like object.x2: It is an array or integer like object that shows the number of bits that will shift right.out=None: It is the object where computed results are stored.where=True: If set to True, it means a universal functionufuncwill be computed for a specific index, otherwise leave the values as it is inout.**kwargs: It is a variable length keyword argument.
Return value
This function returns x1 with bits shifted x2 time to the right. It can either be an ndarray or integer value.
Code example 1
In the below code snippet, right_shift() takes the first argument x1=10 and second x2=1. It shifts
# Program to show working of# right_shift() when arguments are int valuesimport numpy as np# declaring two integersx1= 10x2= 1# show numbers in binary representationprint("Binary of x1:", np.binary_repr(100))print("Binary of x2:", np.binary_repr(1))# invoking right_shift() and printing resultsprint("Right shift Result: ", np.right_shift(x1, x2))
Explanation
- Lines 5 and 6: We define two variables
x1andx2with valuesand assigned to them, respectively.
- Lines 8 and 9: We use
np.binary_repr()to show a binary representation of argument value. Hence, it prints binary ofand . - Line 11: We use
np.right_shift()to shiftx1argumentx2times and show results to console.
Code example 2
Let's look at the code below:
# Program to show working of# right_shift() when arguments are int valuesimport numpy as np# defining integer and an arrayx1= 5000x2 = np.array([8,7,5])# show numbers in binary representationprint("Binary Representation of x1:", np.binary_repr(10))print("Binary Representation of x2:[", end=' ')for i in range(0,len(x2)):print(np.binary_repr(x2[i-1]), end=' ')print("]")# invoking right_shift() and printing resultsprint("Right shifted:", np.right_shift(x1, x2))
Explanation
- Lines 5 and 6: We create
x1andx2two variables withand NumPy array , respectively.
- Lines 8 to 12: We print
x1,x2values in binary representation. - Line 14: We invoke
np.right_shift()to perform right shift operation onx1to shift valuesx2times.
Bitwise >>
In conventional procedural languages, the bit-wise operator >> is used to perform shift-right operations. Hence, we can also use the
# include numpy as alias npimport numpy as np# creating a constant variablex1 = 10# creating a numpy arrayx2 = np.array([1,2,3])# Using bit-wise operatorprint(x1 >> x2)
Explanation
- Line 4: We define
x1and assignvalue.
- Line 6: We define
x2, which contains a NumPy array. - Line 8: We use the bit-wise operator
>>to perform the bitwise right shift.