2

Consider the following numpy array array:

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

which is just an array of four 2's.

I want to perform a bitwise_and reduction of this array:

y = np.bitwise_and.reduce(x)

I expect the result to be:

2

because each element of the array is identical, so successive AND's should yield the same result, but instead I get:

0

Why the discrepancy?

1
  • Related question with a clever workaround in case you are stuck with your current Python installation Commented Dec 7, 2016 at 14:13

1 Answer 1

3

In the reduce docstring, it is explained that the function is equivalent to

 r = op.identity # op = ufunc
 for i in range(len(A)):
   r = op(r, A[i])
 return r

The problem is that np.bitwise_and.identity is 1:

In [100]: np.bitwise_and.identity
Out[100]: 1

For the reduce method to work as you expect, the identity would have to be an integer with all bits set to 1.

The above code was run using numpy 1.11.2. The problem has been 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.