简体   繁体   English

一元运算符〜在numpy中做什么?

[英]What does the unary operator ~ do in numpy?

I came across a line of code using Python's numpy that looked like this: 我使用Python的numpy遇到了如下代码:

~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) 一元运算符(〜)是否接受数组并应用A->-(A + 1)

If so, whats the point? 如果是这样,那有什么意义呢?

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"...). 看起来它将A变成-(A + 1),因为在许多现代计算机上,负数表示为相应正整数的2的补数,其中该数是从2^(bit length)减去的(即“ 2到位长的幂”,而不是“两个异或位长” ...)。

In such a system, -1 would be represented as all ones. 在这样的系统中,-1将被表示为全1。 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. 如您所见。

http://en.wikipedia.org/wiki/Bitwise_operation#NOT 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 http://en.wikipedia.org/wiki/Two%27s_complement

〜是一个补码运算符,如果与int一起使用,它可以在任何python程序中使用(它不仅限于numpy)

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: 对于numpy,它似乎是以下内容的简写:

>>> 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM