减少 NumPy bitwise_and 函数
Reduction of NumPy bitwise_and function
考虑以下 numpy 数组:
x = np.array([2]*4, dtype=np.uint8)
这只是四个 2 的数组。
我想执行此数组的 bitwise_and 缩减:
y = np.bitwise_and.reduce(x)
我希望结果是:
2
因为数组的每个元素都是相同的,所以连续的 AND 应该产生相同的结果,但我得到的是:
0
为什么会出现差异?
在reduce
文档字符串中,说明该函数等价于
r = op.identity # op = ufunc
for i in range(len(A)):
r = op(r, A[i])
return r
问题是np.bitwise_and.identity
是1:
In [100]: np.bitwise_and.identity
Out[100]: 1
要使 reduce
方法按预期工作,标识必须是所有位都设置为 1 的整数。
以上代码 运行 使用 numpy 1.11.2。问题是 fixed in the development version of numpy:
In [3]: np.__version__
Out[3]: '1.13.0.dev0+87c1dab'
In [4]: np.bitwise_and.identity
Out[4]: -1
In [5]: x = np.array([2]*4, dtype=np.uint8)
In [6]: np.bitwise_and.reduce(x)
Out[6]: 2
考虑以下 numpy 数组:
x = np.array([2]*4, dtype=np.uint8)
这只是四个 2 的数组。
我想执行此数组的 bitwise_and 缩减:
y = np.bitwise_and.reduce(x)
我希望结果是:
2
因为数组的每个元素都是相同的,所以连续的 AND 应该产生相同的结果,但我得到的是:
0
为什么会出现差异?
在reduce
文档字符串中,说明该函数等价于
r = op.identity # op = ufunc
for i in range(len(A)):
r = op(r, A[i])
return r
问题是np.bitwise_and.identity
是1:
In [100]: np.bitwise_and.identity
Out[100]: 1
要使 reduce
方法按预期工作,标识必须是所有位都设置为 1 的整数。
以上代码 运行 使用 numpy 1.11.2。问题是 fixed in the development version of numpy:
In [3]: np.__version__
Out[3]: '1.13.0.dev0+87c1dab'
In [4]: np.bitwise_and.identity
Out[4]: -1
In [5]: x = np.array([2]*4, dtype=np.uint8)
In [6]: np.bitwise_and.reduce(x)
Out[6]: 2