Python-Numpy库中的invert()函数的用法


官方解释:


Compute bit-wise inversion, or bit-wise NOT, element-wise.
Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.
For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two’s-complement system can represent every integer in the range −2N−1 -2^{N-1}−2 
 

函数invert()计算输入数组中整数的二进制按位NOT结果. 也就是说 Numpy库中的bitwise_not() 和 invert()是一个函数,作用相同,只是名字不同. 验证一下发现两者其实是相等的:

>>>np.bitwise_not is np.invert
True

下面举例来看invert函数的作用. 官网的例子,我们知道整数"13"以二进制表示为"00001101",将13进行invert()转化有 :

>>> np.invert(np.arange([13], dtype=unit8))
array([242],dtype=unit8)

输出的是242,这个242又是什么呢? 将242转换成二进制数:

>>> np.binary_repr(242, width=8)
'11110010'

这里np.binary_repr() 函数返回给定宽度中十进制数的二进制表示形式。
由输出结果可以发现,"242"的二进制表示“”11110010“”其实就是"00001101"的按位取否.

 

输出的结果取决于bit_width


当dtype取unit16时,结果会变得不同:

>>> np.invert(np.array([13], dtype=uint16))
array([65522], dtype=uint16)
>>> np.binary_repr(x, width=16)
'0000000000001101'
>>> np.binary_repr(65522, width=16)
'1111111111110010'

当使用含符号整数类型"int8"时,结果是无符号类型的结果的二进制补码:

>>> np.invert(np.array([13], dtype=int8))
array([-14], dtype=int8)
>>> np.binary_repr(-14, width=8)
'11110010'

参考资料
【1】 numpy.invert——Numpy

原文:https://blog.csdn.net/Sarah_LZ/article/details/86419606 
 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值