gpt4 book ai didi

python - NumPy bitwise_and 函数的缩减

转载 作者:太空宇宙 更新时间:2023-11-04 00:43:06 24 4
gpt4 key购买 nike

考虑以下 numpy 数组:

x = np.array([2]*4, dtype=np.uint8)

这只是一个由四个 2 组成的数组。

我想对该数组执行按位与缩减:

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

关于python - NumPy bitwise_and 函数的缩减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com