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?