Sum of Boolean Operators on Numpy Bool Arrays (Bug?)

675 Views Asked by At

I've come across a surprising situation when using numpy's arrays. The following code

(True==True)+(True==True)

returns 2, as one would expect. While

import numpy
Array=numpy.zeros((2,2),dtype=bool)
(Array[0][0]==Array[0][0])+(Array[1][0]==Array[1][0])

returns True. This leads to:

(Array[0][0]==Array[0][0])+(Array[1][0]==Array[1][0])-1

returning 0, while

(Array[0][0]==Array[0][0])-1+(Array[1][0]==Array[1][0])

returns 1, making the sum not commutative!

Is this intended? If so, why?

2

There are 2 best solutions below

3
On BEST ANSWER

It would appear that numpy.bool_ behaves slightly differently to vanilla Python bool:

>>> int(True+True) == int(True) + int(True)
True
>>> int(numpy.bool_(1)+numpy.bool_(1)) == int(numpy.bool_(1)) + int(numpy.bool_(1))
False

This is because:

>>> True+True
2
>>> numpy.bool_(1)+numpy.bool_(1)
True
>>> int(numpy.bool_(1)+numpy.bool_(1))
1

Basically, the addition operation for numpy.bool_ is logical, rather than numerical; to get the same behaviour with bool:

>>> int(True and True)
1

This is fine if you only use it for truthiness, as intended, but if you try to use it in an integer context without being explicit about that, you end up surprised. As soon as you're explicit, expected behaviour is restored:

>>> int(numpy.bool_(1)) + int(numpy.bool_(1))
2
0
On

I think the problem is th autocasting.

in this case:

(Array[0][0]==Array[0][0])+(Array[1][0]==Array[1][0])-1
Python do:
(Array[0][0]==Array[0][0])+(Array[1][0]==Array[1][0]) = True
True -1 =cast= 1 -1 = 0

In the second case the cast is do it before:

(Array[0][0]==Array[0][0])-1+(Array[1][0]==Array[1][0])
True - 1 + True 
(True - 1 =cast= 0)
0 + True =cast again=  0+ 1 = 1

So, it's not a bug. It's a autocasting in diferent parts.