Operations cannot be broadcast together with shapes...how?

33 Views Asked by At
x = np.linspace(-10,10, 21) 
z = np.linspace(-10,10, 11) 
V = (1/((5+x)**2+(z)**2)**1.5) - 7.9617*(1/((5-x)**2+(z)**2)**1.5 ) 

error: operands could not be broadcast togetherwith shapes (21,) (11,)

I tried using np.array and np.ndarray but it doesn't work either

1

There are 1 best solutions below

0
ti7 On

The 3rd argument to linspace is how many values to produce, which sets the shape of the resulting array

https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

>>> np.linspace(1, 10, 10)
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
>>> np.linspace(1, 10, 10).shape
(10,)

Oerations which result in broadcasting (such as adding) arrays of different shapes as you're trying to do simply won't work

What do you expect the result to be?

>>> np.linspace(1, 10, 10) + np.linspace(1, 10, 20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (10,) (20,) 
>>> np.linspace(1, 10, 10) + np.linspace(1, 10, 10)
array([ 2.,  4.,  6.,  8., 10., 12., 14., 16., 18., 20.])