I am solving two coupled ordinary differential equations using the 4th-order Runge-Kutta method. I am having trouble in printing the values of z as a result of applying this method. The source code is below for reference. Please, help me fix this code by printing the updated values of z and theta. Thank you.
#Import neeeded modules
import numpy as np
import matplotlib.pyplot as plt
#Input parameters
k = 5 #longitudinal torsional constant
delta = 10**-3 #longitudinal torsional constant
I = 10**-4 #Rotational Inertia
eps = 10**-2 #Coupling constant
m = 0.5
#Time Step
#Setting time array for graph visualization
dt = 0.002 #Time Step
tStop = 0.30 #Maximum time for graph visualization derived from Kinematics
t = np.arange(0., tStop+dt, dt) #Array of time
z = np.zeros(len(t))
dz = np.zeros(len(t))
theta = np.zeros(len(t))
dtheta = np.zeros(len(t))
#Functions that include the equations of motion
def dYdt(t,u):
z, dz, theta, dtheta = u
ddz = -(k*z+0.5*eps*theta)/m
ddtheta = -(delta*theta+0.5*eps*z)/I
return np.array([dz, ddz, dtheta, ddtheta])
def rk4(t, u, dt):
for i in range(len(t)-1):
# runge_kutta
k1 = dYdt(t[i], u[i])
k2 = dYdt(t[i] + dt/2, u[i] + dt/2 * k1)
k3 = dYdt(t[i] + dt/2, u[i] + dt/2 * k2)
k4 = dYdt(t[i] + dt, u[i] + dt * k3)
u.append(u[i] + (k1 + 2*k2 + 2*k3 + k4) * dt / 6)
#Unpacking
z, dz, theta, dtheta = np.asarray(u).T
print(z)
Here are the equations of motions I used to come up with the source code. Coupled ODEs
This is what I THINK you want, but I don't know what parameters to pass to
rk4
. Also,u
is a 1D vector, so I don't know what you were expectingz, dz, theta, dtheta = np.asarray(u).T
to do. As a result, this code won't run, but it will show you a potential design.