如何将这种Runge-Kutta方法实现从一阶ode求解器更改为ODE求解器系统?

时间:2019-04-24 08:04:04

标签: python modeling ode runge-kutta

我对初始条件为u(x0)= u0的函数u'(x)= f(x,u(x))实现了四步Runge-Kutta方法(k1..k4)ODE求解器>

但是它只解决一阶ODE。我如何更改代码,使其也需要更高的ODE? u '(x)= f (x, u (x)),初始条件为u(x0)= u0 ?所有都是向量,这里不是标量。

这是我的解决方案的代码,其中包含一阶ODE:

def euler(f, x, y, h):
    yn = y + h*f(x,y)
    xn = x + h
    return xn, yn

def rk4(f, x, y, h):
    k1 = h*f(x,y)
    k2 = h*f(x+(1/2)*h,y+(1/2)*k1) 
    k3 = h*f(x+(1/2)*h,y+(1/2)*k2)
    k4 = h*f(x+h,y+k3)
    yn = y + ((1/6)*(k1+(2*k2)+(2*k3)+k4))
    xn = x + h
    return xn, yn

def integrate(method, f, t0, y0, tend, h): # Depending on the 'method' (euler or rk4) this method solves the ode f)
    T = [t0]
    Y = [y0]
    t = t0
    y = y0 
    while (t < tend):
        h = min(h, tend-t)
        t, y = method(f, t, y, h)
        T.append(t)
        Y.append(y)
    return np.array(T), np.array(Y)

def f1(t, y):   # this is an 1st order ODE
    return (t*y) + t

# Usage example
xv, yv = integrate(method=rk4, f=f1, t0=0, y0=2, tend=1, h=0.5)
yv[-1] # Output: 6.15203857421875

是否有解决方案,也可以针对给定的ODE系统进行这项工作? (动态地,不知道输入的ODE是一阶还是更高阶),例如: u′′(x)+ u(x)+ u(x)^ 3 = 0且u(0)= u′(0)= 0 或这一个: u'1(x)= 98u1(x)+ 198u2(x)和u'2(x)= −99u1(x)− 199u2(x),其中u1(0)= 1和u2(0)= 0

0 个答案:

没有答案