Search code examples
pythonarrayspython-2.7numpyboolean-operations

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


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?


Solution

  • 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