numpy.bitwise_and.reduce表现异常?

发布于 2021-01-29 16:38:29

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
关注者
0
被浏览
48
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    根据您提供的文档,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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看