numpy.invert() in Python
This tutorial focuses on the invert()
function from the NumPy module of Python.
In numpy.invert() function, the function returns the bit-wise inversion of each element present in an array. In other words, we can say we can compute the bit-wise NOT of the binary representation of each element present in the array. It also returns the two’s complements for the signed integer.
Working of numpy.invert()
CASE 1:
Suppose, we have number 10 and we want its bitwise inversion. The binary form of 10 is 00001010 and after the inversion of each bit, it results in 11110101 which is number -11.
As we know the binary of number 11 is 00001011. We will now find its two’s complement. The two’s complement of 11 will result in -11 which is the same as the bitwise inversion of the number 10.
Python code for the above explanation:
import numpy as np num = 10 rrsult = np.invert(num) print ("inversion of 10 : ", result)
Output:
inversion of 10 : -11
CASE 2:
In numpy.invert()
function we can also pass an array of numbers which will result in bitwise inversion of each element present in the array.
Code for the above statement –
import numpy as np lst = [3, 10, 21] res_lst = np.invert(lst) print ("Output list after inversion: ", res_lst)
Output:
Output list after inversion: [ -4 -11 -22]
In the above code, the list of numbers is passed in the function and the function returned bitwise NOT of each number and we stored the result in “res_lst”.
CASE 3:
numpy.invert()
functions also invert the boolean expression i.e if the input if true then the function will return false and if the input is false the function will return a true value.
Code for the above statement:
import numpy as np lst = [True, False] res_lst = np.invert(lst) print ("Output list after inversion: ", res_lst)
Output:
Output list after inversion: [False True]
Hence we understood how numpy.invert()
function works and where it is used.
Leave a Reply