tags:

views:

96

answers:

5

I came across a line of code using Python's numpy that looked like this:

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

And it gave the output:

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

Does the unary operator (~) take an array and apply A -> -(A+1)

If so, whats the point?

+4  A: 

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

The reason why you end up with negative numbers is how they are represented in binary form:

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

relet
+9  A: 

Chris Lutz' comment is correct.

~ is the bitwise negation operator

It looks like it turns A to -(A+1) because on many modern computers, negative numbers are represented as the Two's Complement of the corresponding positive integer, where the number is subtracted from 2^(bit length) (that's "two to the power of bit length", not "two exclusive or bit length"...).

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

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

as you noticed.

Blair Conrad
A: 

The point is to be able to take the complement of the vales in an array. In the case of numpy it appears to be shorthand 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]
Noah Watkins
+1  A: 

I'M 90% sure it get's ones-compliment of the number... but I could be wrong.

Ranman
+1  A: 

The ~ is the ones' complement operator and if you're using with ints it can be used in any python program (it's not exclusively of numpy)

Ed
I'm not so sure, the following line:~list[1,2,3]fails since the unary operator was not defined for lists, the class object has to have them defined just like any other operator.
Hooked
you're right, I haven't checked it with lists
Ed