numpy.bitwise_and.reduce意外表现?

时间:2014-01-10 17:41:17

标签: python python-2.7 numpy reduce accumulate

numpy.bitwise_and.reduce的ufunc.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()的最后一个值,而不是>>> ~np.bitwise_or.reduce(np.invert(x)) 17 。我在这里缺少什么?

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

{{1}}

1 个答案:

答案 0 :(得分:2)

根据您提供的文档,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不同)

相关问题