Reputation: 43
Einstein summation (numpy.einsum) of boolean arrays in numpy doesn't produce expected results. Numpy.einsum function does logical operations on boolean arrays, which is questionable in the numeric contexts.
# summation of a boolean numpy array
x = numpy.array([True, False, True])
print(numpy.sum(x))
# output: 2
print(numpy.einsum('i->', x))
# output: True
For a boolean array x = [True, False, True], I expect that the summation of x is 2, and the result should not depend on the particular choice of the function. However, numpy.sum gave 2, and numpy.einsum gave True.
I am not sure whether I misunderstood something or there is some problem with my code. Any help is appreciated.
Upvotes: 4
Views: 295
Reputation: 8277
The difference here is that sum
casts the boolean
into integers before summing, while einsum
skips this step except if you specify it explicitly.
Try:
print(numpy.einsum('i->', x, dtype=int))
Upvotes: 4