NumPy left_shift() function
In this tutorial, we will cover the left_shift
that is a binary operation of the Numpy library.
In Numpy, the left_shift()
function is mainly used to perform the left shift operation.
Syntax of numpy.left_shift()
:
The syntax required to use this function is as follows:
numpy.left_shift(x1, x2, /, out, *, where, casting='same_kind', order='K', dtype, ufunc 'left_shift')
As the internal representation of numbers is mainly in the binary format, thus left shift operation is equivalent to multiplying x1 by 2**x2.
With the help of this function, the bits are shifted to the left just by appending x2 number of 0s(zeroes) at the right of x1.
Parameters:
Let us now take a look at the parameters of this function:
-
x1
This parameter is used to represent the input value and it is in the form of an array.
-
x2
This parameter is used to indicate the number of bits to append at the right of x1. It must be a non-negative number. If x1.shape != x2.shape
, then they must be broadcastable to a common shape and that shape becomes the shape of the output.
-
out
This parameter indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
-
where
This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the ufunc result, else the out array will retain its original value.
Returned Values:
This function will return x1
with bits shifted x2
times to the left. The returned value is a scalar if both x1
and x2
are scalars.
Example 1:
In the example below, we will illustrate the usage of left_shift()
function:
import numpy as np
input_num = 40
bit_shift = 2
print ("The Input number is: ")
print(input_num)
print ("The Number of bit shift : ")
print(bit_shift )
output = np.left_shift(input_num, bit_shift)
print ("After the shifting of 2 bits to left : ")
print(output)
The Input number is:
40
The Number of bit shift :
2
After the shifting of 2 bits to left :
160
Example 2:
Now we will show you a code snippet where we will apply left_shift()
on to an input array:
import numpy as np
input_arr = [2, 8, 10]
bit_shift =[3, 4, 5]
print ("The Input array is: ")
print(input_arr)
print ("The Number of bit shift : ")
print(bit_shift )
output = np.left_shift(input_arr, bit_shift)
print ("After left shifting of bits,the output array is: ")
print(output)
The Input array is:
[2, 8, 10]
The Number of bit shift :
[3, 4, 5]
After left shifting of bits,the output array is:
[ 16 128 320]
Summary
In this tutorial, we covered the left_shift()
function of the NumPy library. We covered its basic syntax and parameters and then the values returned by this function along with a few code examples for the function.