问题描述
我正在尝试通过 runge-kutta 4 阶方法在数值上求解两个 ode 的系统.初始系统:系统解决:
I'm trying to solve system of two odes numerically by runge-kutta 4th order method.initial system:system to solve:
而且我有非常奇怪的解决方案图...我有:
And I have very strange solution graph...I have:
正确的图形:
我在我的 runge-kutta 中找不到问题.请帮帮我.
I can't find trouble in my runge-kutta. Please, help me.
我的代码在这里:
dt = 0.04
#initial conditions
t.append(0)
zdot.append(0)
z.append(A)
thetadot.append(0)
theta.append(B)
#derrive functions
def zdotdot(z_cur, theta_cur):
return -omega_z * z_cur - epsilon / 2 / m * theta_cur
def thetadotdot(z_cur, theta_cur):
return -omega_theta * theta_cur - epsilon / 2 / I * z_cur
i = 0
while True:
# runge_kutta
k1_zdot = zdotdot(z[i], theta[i])
k1_thetadot = thetadotdot(z[i], theta[i])
k2_zdot = zdotdot(z[i] + dt/2 * k1_zdot, theta[i])
k2_thetadot = thetadotdot(z[i], theta[i] + dt/2 * k1_thetadot)
k3_zdot = zdotdot(z[i] + dt/2 * k2_zdot, theta[i])
k3_thetadot = thetadotdot(z[i], theta[i] + dt/2 * k2_thetadot)
k4_zdot = zdotdot(z[i] + dt * k3_zdot, theta[i])
k4_thetadot = thetadotdot(z[i], theta[i] + dt * k3_thetadot)
zdot.append (zdot[i] + (k1_zdot + 2*k2_zdot + 2*k3_zdot + k4_zdot) * dt / 6)
thetadot.append (thetadot[i] + (k1_thetadot + 2*k2_thetadot + 2*k3_thetadot + k4_thetadot) * dt / 6)
z.append (z[i] + zdot[i + 1] * dt)
theta.append (theta[i] + thetadot[i + 1] * dt)
i += 1
推荐答案
您的状态有 4 个组件,因此您在每个阶段都需要 4 个斜坡.很明显,z
的斜率/更新不能来自 k1_zdot
,它必须是 k1_z
之前要计算的
Your state has 4 components, thus you need 4 slopes in each stage. It should be obvious that the slope/update for z
can not come from k1_zdot
, it has to be k1_z
which is to be computed previously as
k1_z = zdot
进入下一阶段
k2_z = zdot + dt/2*k1_zdot
等
但最好使用矢量化界面
def derivs(t,u):
z, theta, dz, dtheta = u
ddz = -omega_z * z - epsilon / 2 / m * theta
ddtheta = -omega_theta * theta - epsilon / 2 / I * z
return np.array([dz, dtheta, ddz, ddtheta]);
然后使用 RK4 的标准公式
and then use the standard formulas for RK4
i = 0
while True:
# runge_kutta
k1 = derivs(t[i], u[i])
k2 = derivs(t[i] + dt/2, u[i] + dt/2 * k1)
k3 = derivs(t[i] + dt/2, u[i] + dt/2 * k2)
k4 = derivs(t[i] + dt, u[i] + dt * k3)
u.append (u[i] + (k1 + 2*k2 + 2*k3 + k4) * dt / 6)
i += 1
然后解压为
z, theta, dz, dtheta = np.asarray(u).T
这篇关于Runge-Kutta 4th order 使用 Python 解决二阶 ODE 系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!