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
Code:
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:
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,)
CodePudding user response:
You're either missing a pair of parentheses:
for i in range(len(time_arr)):
# v v
res_arr[i 1] = (res_arr[i] pend_func(res_arr[i-1], time_arr[i-1], l, m, g, mu)) * dt
# ^ ^
Or you need to convert the return type of pend_func
to np.array
:
for i in range(len(time_arr)):
# vvvvvvvvv v
res_arr[i 1] = res_arr[i] np.array(pend_func(res_arr[i-1], time_arr[i-1], l, m, g, mu)) * dt
# ^^^^^^^^^ ^
Both will solve the problem, but they'll produce different results, so I'm not sure which one is appropriate for your purpose.
CodePudding user response:
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]]
to
return [d1, d2]