Numpy element wise division not working as expected

numpy, python

Solution

This is because the shapes of your two arrays are t.shape = (3,1) and s.shape=(3,). So the broadcasting rules apply: They state that if the two dimensions are equal, then do it element-wise, if they are not the same it will fail unless one of them is one, an this is where it becomes interesting: In this case the array with the dimension of one will iterate the operation over all elements of the other dimension.

I guess what you want to do would be

t[:,0] / s

or

np.squeeze(t) / s

Both of which will get rid of the empty first dimension in t. This really is not a bug it is a feature! because if you have two vectors and you want to do an operation between all elements you do exactly that:

a = np.arange(3)
b = np.arange(3)

element-wise you can do now:

a*b = [0,1,4]

If you would want to do have this operation performed between all elements you can insert these dimensions of size one like so:

a[np.newaxis,:] * b[:,np.newaxis]

Try it out! It really is a convenient concept, although I do see how this is confusing at first.

Problem

From the docs, here is how element division works normally ``` a1 = np.array([8,12,14]) b1 = np.array([4,6,7]) a1/b1 array([2, 2, 2]) ``` Which works. I am trying the same thing, I think, on different arrays and it doesn't. For two 3-dim vectors it is returning a 3x3 matrix. I even made sure their "shape is same" but no difference. ``` >> t array([[ 3.17021277e+00], [ 4.45795858e-15], [ 7.52842809e-01]]) >> s array([ 1.00000000e+00, 7.86202619e+02, 7.52842809e-01]) >> t/s array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00], [ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15], [ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]]) t/s.T array([[ 3.17021277e+00, 4.03231011e-03, 4.21098897e+00], [ 4.45795858e-15, 5.67024132e-18, 5.92149984e-15], [ 7.52842809e-01, 9.57568432e-04, 1.00000000e+00]]) ```

Original source