Reputation: 189
I want to solve the equation y'' + 5y' + 6y = cos(t). Since this is 2nd order, I first created a system of first order ODEs where dy/dt = z = f(t,y,z) and dz/dt = cos(t) - 5z - 6y = g(t,y,z). I'm a novice with python, and unsure how exactly to implement the program with a system of ODEs, but for my inputs I wrote func = [f,g] and ic = [y0,dy0].
Secondly, since Runge Kutta evaluates variable expression whose values are only available during runtime, I am using python's eval function, though I am receiving an error. Below is my code and the error message:
def f(t,y,z):
return z
def g(t,y,z):
return np.cos(t)-5*z-6*y
t = np.linspace(0,20,100)
y = np.zeros((1,len(t)))
z = np.zeros((1,len(t)))
fun = [f(t,y,z),g(t,y,z)]
ic = [1,0] # y0,dy0
def ruku(fun,h):
t0=0
tf=20
t=t0
y=ic
fc=0
while t < tf:
if t+h > tf:
exit()
if h == tf-t:
exit()
k1=eval('fun',t,y)
k2=eval('fun',t+h/3,y+h*k1/3)
k3=eval('fun',t+2*h/3,y+h*(k2-k1/3))
k4=eval('fun',t+h,y+h*(k3-k2+k1))
y=y+h*(k1+3*(k2+k3)+k4)/8
fc=fc+4
t=t+h
return y
ruku(fun,0.01)
-->TypeError: globals must be a dict
Thanks in advance for any suggestions; I'm really trying to make this work.
Upvotes: 3
Views: 211
Reputation: 189
Turns out I was underestimating the simplicity of Python! Replaced my loop with:
while t +h <= tf:
k1=fun(t,y)
k2=fun(t+h/3,y+h*k1/3)
k3=fun(t+2*h/3,y+h*(k2-k1/3))
k4=fun(t+h,y+h*(k3-k2+k1))
y=y+h*(k1+3*(k2+k3)+k4)/8
fc=fc+4
t=t+h
and converted my inputs into np.arrays
Upvotes: 3