Sum of boolean operators on Bool Numpy arrays (error?)
I ran into an amazing situation when using numpy
array
s. The following code
(True==True)+(True==True)
returns 2
as you 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
returns 0
, and
(Array[0][0]==Array[0][0])-1+(Array[1][0]==Array[1][0])
returns 1
, making the amount not commutative!
Is this intended? If so, why?
source to share
It looks like it numpy.bool_
behaves slightly differently in relation 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, not numeric; to get the same behavior with bool
:
>>> int(True and True)
1
It's fine if you only use it for truthfulness as intended, but if you try to use it in an integer context without being explicit about it, you end up wondering. Once you are explicit, the expected behavior will be restored:
>>> int(numpy.bool_(1)) + int(numpy.bool_(1))
2
source to share
I think the problem is with autorun.
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 does it earlier:
(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 this is not a mistake. It's autoloading in different parts.
source to share