为什么RK4无法解决此ODE?

时间:2019-07-29 20:01:12

标签: python numerical-methods ode differential-equations

我正在尝试使用RK4解决ODE:

x'(t) + 0.5 x'(t) **2 + x = 0

并绘制图x'(x)。

def RK4 (t, dt, s):
    w = np.zeros(len(s))
    k1 = np.zeros(len(s))
    k2 = np.zeros(len(s))
    k3 = np.zeros(len(s))
    k4 = np.zeros(len(s))

    for i in range(len(s)):
        w[i]= s[i]
    diff (t, w, k1)
    for i in range(len(s)):
        w[i]= s[i] + dt/2*k1[i]
    diff (t+dt/2, w, k2)
    for i in range(len(s)):
        w[i]= s[i] + dt/2*k2[i]
    diff (t+dt/2, w, k3)
    for i in range(len(s)):
        w[i]= s[i] + dt*k3[i]
    diff (t+dt, w, k4)
    for i in range(len(s)):
        s[i] = s[i] + dt/6 * (k1[i]+ 2*k2[i]+ 2*k3[i] + k4[i])

def diff (t, s, k):
    k[0] = s[1]
    k[1] = -0.5*s[1]*s[1]-s[0]

def scheme(dt, s, x, p):

    t = 0

    s[0] = 2
    s[1] = 2

    x[0] = s[0]
    p[0] = s[1]

    for i in range(int(t_max/dt)):
        RK4(t, dt, s)
        t = t + dt

        x[i+1] = s[0]
        p[i+1] = s[1]

N     = 2
s     = np.zeros(N)
t_max = 100
dt    = 0.01

x    = np.zeros(int(t_max/dt)+1)
y    = np.zeros(int(t_max/dt)+1)

我写了代码,但是我的情节并不像我预期的那样。 X和Y轴显示非常大的数字(例如〜exp(50))。而且,我可以看到警告:

RuntimeWarning: overflow encountered in double_scalars. 

我的情节是直线,我希望轨道是封闭的。

0 个答案:

没有答案