python - numpy.bitwise_and.reduce 行为异常?

标签 python python-2.7 numpy reduce accumulate

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.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 不同)

关于python - numpy.bitwise_and.reduce 行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050875/

相关文章:

python - 无法使用查找我的设备功能给我的手机响铃。事实上它甚至没有登录

python - 具有稀疏矩阵的 numpy 元素外积

python - 如何将参数传递给已加载的 tensorflow 图(在内存中)

python - 如何注册MultipleModelAPIView?

linux - Python读取Linux内存过程报错(/proc/$pid/mem)

python - 3D Polar Plot - griddata 不允许三次插值,只有线性插值导致 "unsmooth"图

python - Selenium Python 无法在 ConnectWise 登录页面上选择元素

python - raw_input在cpython源代码中哪里实现的?

python - 将 3D numpy 数组保存到 .txt 文件

python - 无法正确展开 numpy 数组