What does the unary ~ operator do in numpy?

I came across a line of code using Python numpy, which looked like this:

~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2]) 

And he gave the result:

 array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1]) 

The unary operator (~) takes an array and applies A β†’ - (A + 1)

If so, what is the point?

+7
python numpy
source share
4 answers

Comment by Chris Lutz.

~ - bitwise negation operator

It looks like it turns A into - (A + 1), because on many modern computers negative numbers are represented as Two Complement the corresponding positive integer, where the number is subtracted from 2^(bit length) (which is β€œtwo for the power of bit length” , not "two exceptional or bit lengths ...).

In such a system, -1 will be represented as all. Of course, so is the sum of the number and its bitwise negative, so we have a situation where

 a + ~a = -1 => ~a = -1 - a => ~a = -(a + 1) 

as you noticed.

+14
source share

http://en.wikipedia.org/wiki/Bitwise_operation#NOT

The reason you get negative numbers is because they are represented in binary form:

http://en.wikipedia.org/wiki/Two%27s_complement

+4
source share

~ is one of them , and if you use with ints, it can be used in any python program (this is not exclusively from numpy)

+2
source share

The point is to be able to accept additions to vales in an array. In the case of numpy, this means shortening for the following:

 >>> map(lambda e: ~e, [0,1,2,3,4,5,4,3,2,1,0,-1,-2]) [-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1] 
0
source share

All Articles