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.identity
是 1
,而不是 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
不同)
关于python - numpy.bitwise_and.reduce 行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050875/