numpy.bitwise_and.reduce表现异常?


问题内容

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.identity1,不是,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