I've come across a surprising situation when using numpy
's array
s. 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?
It would appear that
numpy.bool_
behaves slightly differently to vanilla Pythonbool
:This is because:
Basically, the addition operation for
numpy.bool_
is logical, rather than numerical; to get the same behaviour withbool
: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: