一元运算符〜在numpy中做什么? [英] What does the unary operator ~ do in numpy?

查看:90
本文介绍了一元运算符〜在numpy中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python的numpy遇到了如下代码:

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

它给出了输出:

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

一元运算符(〜)是否接受数组并应用A->-((A + 1)

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

如果是这样,那有什么意义?

If so, whats the point?

推荐答案

克里斯·卢茨(Chris Lutz)的评论正确.

Chris Lutz' comment is correct.

〜是按位求反运算符

它看起来像将A变成-(A + 1),因为在许多现代计算机上,负数表示为相应正整数的二进制补码,其中的数字是从2^(bit length)中减去的(即两位乘以位长的幂",而不是两位互斥或位长" ...)

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"...).

在这样的系统中,-1表示为全1. 当然,一个数字与它的按位负数的和也是如此,所以我们有这样的情况

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)

您注意到了.

这篇关于一元运算符〜在numpy中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆