4

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 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

Do you know if there is a reason why numpys bool was designed to behave different than vanillas bool? Or wasn't the sum of bools intended in vanillas bool either? Maybe no one had given it a thought ^^
I don't, no. There is some discussion about removing these operators here, if you're interested.
Thanks for your answer, this motivated me to write cleaner and prettier Python code. Even more so after seeing all the other issues I hadn't noticed (and probably would never notice).
1

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.

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.