2014-01-10 107 views
2

numby.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()的最后一个值,它不是。我在这里错过了什么?

就目前而言,我可以解决使用德摩根的身份(交换或与AND和反相输入端和输出):

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

从版本1.12.0开始,您应该看到'np.bitwise_and'的标识的正确值(-1)。参见[PR#7373](https://github.com/numpy/numpy/pull/7373)。顺便说一下,非常酷的解决方法! –

回答

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

+1

啊,明白了。谢谢。这是一个耻辱ufunc.reduce不允许明确的初始值参数。 –

+0

@JasonS,是的,如果'ufunc.reduce'允许我们指定初始值,那就太好了。 – falsetru

+0

在过去的几年中,这有所改变吗? –