2014-01-10 106 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

在過去的幾年中,這有所改變嗎? –