Does numpy broadcast in *all* of its functions?

124 Views Asked by At

Say I have two objects X, Y of shape k,1,n and k,m,n. I know that numpy will automatically extend/repeat X along the first dimension when I do operations such as X + Y. Does this magic work for all mathematical operations that are supported/included in numpy?

For example, can I do scipy.special.binom(X,Y) and get the expected result? I have tried some of the special functions, and I don't receive an error. Does not receiving an error allow me to conclude that the broadcasting was done correctly?

1

There are 1 best solutions below

0
On

numpy does apply broadcasting for all operators, eg. *+-/ etc. It also applies it where possible to ufunc functions. That's part of the ufunc definition.

scipy.special.binom is, according to its docs a ufunc. It is compiled so I can't look at the code to verify this, but I can do a few simple tests:

In [379]: special.binom([1,2,3],[[1],[2]])
Out[379]: 
array([[ 1.,  2.,  3.],
       [ 0.,  1.,  3.]])

In [380]: special.binom([1,2,3,4],[[1],[2]])
Out[380]: 
array([[ 1.,  2.,  3.,  4.],
       [ 0.,  1.,  3.,  6.]])

In [385]: special.binom(np.arange(6).reshape(3,2,1),np.arange(6).reshape(3,1,2)).shape
Out[385]: (3, 2, 2)

The (2,3) and (2,4) output dimensions match the broadcasted inputs. That consistent with broadcasting.

np.dot is an example of a numpy function where broadcasting does not apply.