gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:31 26 4
gpt4 key购买 nike

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/

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