问题
The ufunc.reduce for numpy.bitwise_and.reduce does not appear to behave properly... am I misusing it?
>>> 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'
The result of reduce()
should be the last value of accumulate()
and it's not. What am I missing here?
For the moment, I can work around by using DeMorgan's identity (swapping OR and AND, and inverting input and output):
>>> ~np.bitwise_or.reduce(np.invert(x))
17
回答1:
According to the documentation you provided, ufunc.reduce
uses op.identity
as an initial value.
numpy.bitwise_and.identity
is 1
, not 0xffffffff....
nor -1
.
>>> np.bitwise_and.identity
1
So numpy.bitwise_and.reduce([0x211f,0x1013,0x1111])
is equivalent to:
>>> np.bitwise_and(np.bitwise_and(np.bitwise_and(1, 0x211f), 0x1013), 0x1111)
1
>>> 1 & 0x211f & 0x1013 & 0x1111
1
>>> -1 & 0x211f & 0x1013 & 0x1111
17
There seems to be no way to specify the initial value according to the documentation. (unlike Python builtin function reduce)
来源:https://stackoverflow.com/questions/21050875/numpy-bitwise-and-reduce-behaving-unexpectedly