Reputation: 1214
I keep getting a ValueError when working with numpy arrays and I can't figure out what's causing it, as it seems to be working correctly outside of my for loop. Here is my code:
import numpy as np
def x(t, x_0, w):
return x_0*np.cos(w*t)
def x_prime(t, x_0, w):
return -x_0*w*np.sin(w*t)
w = 1
x_0 = 1
h = 0.001
t = np.arange(0, 10, h)
y = np.array([[0, 0]]*len(t))
y[0] = [x_0, 0]
# The line below works correctly, but not inside my loop
print np.array([x_prime(1, x_0, w), -w**2 * x(1, x_0, w)])*h + y[0]
for i in range(1, len(t)):
# Euler's method
y[i] = y[i-1] + np.array([x_prime(t, x_0, w), -w**2 * x(t, x_0, w)]) * h
From the print
line I get this output: [ 9.99158529e-01 -5.40302306e-04]
, so that seems to be working correctly. However, I'm getting this error at the y[i]
line:
ValueError: operands could not be broadcast together with shapes (2,) (2,10000)
I'm not sure why, since my print statement earlier is basically doing the same thing, and y[i]
should be the same shape. Does anyone know what the problem is?
Upvotes: 0
Views: 612
Reputation: 126
No idea what your algorithm try to realize, but your seems to use all the t in one iteration, maybe my change can help you. import numpy as np
def x(t, x_0, w):
return x_0*np.cos(w*t)
def x_prime(t, x_0, w):
return -x_0*w*np.sin(w*t)
w = 1
x_0 = 1
h = 0.001
t = range(0, int(10/h))
y = np.array([[0, 0]]*len(t))
y[0,0] = x_0
y[0,1] = 0
# The line below works correctly, but not inside my loop
print(np.array([x_prime(1, x_0, w), -w**2 * x(1, x_0, w)])*h + y[0])
for i in range(1, len(t)):
# Euler's method
y[i] = y[i-1] + np.array([x_prime(t[i]*h, x_0, w), -w**2 * x(t[i]*h, x_0, w)]) * h
Upvotes: 0
Reputation: 18950
In the print
line the first argument of x()
/x_prime()
is a scalar (1
).
In the y[i]
line you pass t
instead, which is a 10000-elements array, resulting in np.array([x_prime(t, x_0, w), -w**2 * x(t, x_0, w)])
being a (2,10000) matrix, hence the ValueError
.
Perhaps what you want to do is:
y[i] = y[i-1] + np.array([x_prime(t[i], x_0, w), -w**2 * x(t[i], x_0, w)]) * h
Upvotes: 1