Skip to main content
 首页 » 编程设计

python之numpy.bitwise_and.reduce 行为异常

2024年11月01日952php

ufunc.reduce因为 numpy.bitwise_and.reduce 似乎表现不正常……我是在滥用它吗?

>>> import numpy as np 
>>> x = [0x211f,0x1013,0x1111] 
>>> np.bitwise_or.accumulate(x) 
array([ 8479, 12575, 12575]) 
>>> np.bitwise_and.accumulate(x) 
array([8479,   19,   17]) 
>>> '%04x' % np.bitwise_or.reduce(x) 
'311f' 
>>> '%04x' % np.bitwise_and.reduce(x) 
'0001' 

reduce() 的结果应该是 accumulate() 的最后一个值,但事实并非如此。我在这里缺少什么?

目前,我可以通过使用 DeMorgan 的身份(交换 OR 和 AND,以及反转输入和输出)来解决问题:

>>> ~np.bitwise_or.reduce(np.invert(x)) 
17 

请您参考如下方法:

根据您提供的文档,ufunc.reduce 使用 op.identity 作为初始值。

numpy.bitwise_and.identity 是 1,不是 0xffffffff.... 也不是 -1。

>>> np.bitwise_and.identity 
1 

所以 numpy.bitwise_and.reduce([0x211f,0x1013,0x1111]) 等同于:

>>> np.bitwise_and(np.bitwise_and(np.bitwise_and(1, 0x211f), 0x1013), 0x1111) 
1 
>>> 1 & 0x211f & 0x1013 & 0x1111 
1 

>>> -1 & 0x211f & 0x1013 & 0x1111 
17 

根据文档似乎没有办法指定初始值。 (不同于 Python 内置函数 reduce )