Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy scalars, broadcasting and the __iadd__ method

Tags:

python

numpy

Any ideas on this oddity?

from numpy import *

a = array([1,2])
b = 1
b += a

gives array([2,3]), as you would expect. But

a = array([1,2])
b = array(1)
b += a

gives the error "non-broadcastable output operand with shape () doesn't match the broadcast shape (2)". At the same time

a = array([1,2])
b = array(1)
b = b + a

gives array([2,3]). Is this behaviour as odd as it looks at first glance?

Thanks in advance.

like image 389
n00b Avatar asked Dec 02 '25 12:12

n00b


1 Answers

The += operator is taken to mean "in-place summation". Numpy imposes some constraints as to what in-place means: it cannot change the size or dtype of the array. When you do b = b + a there is no problem, because b now points to a new object resulting from adding b and a, which is a length 2 array. It is not surprise that b += a fails, since the length 2 array cannot be fitted into the length 1 array.

As for your first test case, my guess is that since Python ints are immutable objects, whenever you __iadd__ to one, you are effectively creating a new object and pointing to it, not modifying the object you had, so there is no reason why it shouldn't work with an array.

like image 169
Jaime Avatar answered Dec 05 '25 01:12

Jaime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!