[SOLVED] Numpy Error: Operands could not be broadcast together with shapes (2,) (0,)


I am trying to create a 2d-array with values taken from the array’s previous value, added to values computed from a function. I am however getting the error :

ValueError: operands could not be broadcast together with shapes (2,) (0,) 

Now while I know what the error means, I can’t seem to find where the problem is exactly or how to fix it.

The program’s use is to create a custom euler solver which adds previous values of the array with the function


import numpy as np
from scipy.integrate import odeint

def func(): 
    d1 = #equation
    d2 = #equation
    return [[d1], [d2]]

l = 1
m = 1
g = 1
mu = 1

max = 1

arr_in = np.array(1, 1)

arr_2 = np.linspace(1, 4, maxx) 
dt = 1

arr_out = np.zeros((max, 2))
arr_out[0] = arr_in[0]
for i in range(len(arr_2)):
    arr_out[i+1] = arr_out[i] + func(arr_out[i-1], arr_2[i-1], l, m, g, mu) * dt


Traceback (most recent call last):
  File "task3.py", line 31, in <module>
    res_arr[i] = solver(res_arr, i)
ValueError: could not broadcast input array from shape (2,2) into shape (2,)


The issue was that the pend_func function was returning an array of a different shape than the rest of the arrays. This was fixed by changing

return [[d1], [d2]]


return [d1, d2]

Answered By – mkdirBed

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *