如何求解R中的二阶微分方程?

时间:2017-09-06 11:56:55

标签: python r ode differential-equations

我正在学习 R 来解决二阶微分方程(可能使用deSolve包)。我将它写成python,将其写成两个一阶微分方程,并在下面给出

import  numpy  as np
import  matplotlib.pyplot  as plt
from  scipy.integrate  import  odeint

def  fun(X, t):
    y , dy , z = X
    M = np.sqrt (1./3. * (1/2. * dy **2 + 1./2.  * y **2))
    dz = (M*z) # dz/dt
    ddy =  -3.* M * dy -  y # ddy/dt

    return [dy ,ddy ,dz]

y0 = 1

dy0 =  -0.1

z0 = 1.

X0 = [y0, dy0, z0]

M0 = np.sqrt (1./3. * (1./2. *  dy0 **2. + 1./2.*  y0 **2)) 

t = np.linspace(0., 100., 10001.) # time spacing

sol = odeint(fun, X0, t)

y = sol[:, 0]

dy = sol[:, 1]

z = sol[:, 2]

M = np.sqrt (1./3. * (1./2. *  dy**2. + 1./2.*  y **2)) 

#Graph plotting
plt.figure()
plt.plot(t, y)
plt.plot(t, z)
plt.plot(t, M)
plt.grid()
plt.show()

Python 很容易解决这个问题,但是对于另一个类似但复杂的问题,python显示错误。我也在python中尝试过ode(vode / bdf),但问题仍然存在。现在,我想查看 R 如何解决问题。所以,如果有人请给我一个如何在 R 中解决此问题的示例(基本上是代码翻译!),我将非常感激,这样我就可以尝试其他一个在 R 中,并且还学习了一些 R (我知道这可能不是学习a的理想方式式语言)。

我知道这个问题可能没什么建设性价值,但我只是 R 的新手,所以请耐心等待我!

1 个答案:

答案 0 :(得分:2)

这应该是Python代码到R

的翻译
library(deSolve)

deriv <- function(t, state, parameters){
  with(as.list(c(state, parameters)),{

    M <- sqrt(1/3 * (1/2 * dy^2 + 1/2 * y^2))
    dz <- M*z # dz/dt
    ddy <-  -3* M * dy -  y # ddy/dt

    list(c(dy, ddy, dz))

  })
}

state <- c(y = 1,
           dy = -0.1,
           z = 1)

times <- seq(0, 100, length.out = 10001)

sol <- ode(func = deriv, y = state, times = times, parms = NULL)

y <- sol[, "y"]

dy <- sol[, "dy"]

z <- sol[, "z"]

M <- sqrt(1/3 * (1/2 *  dy^2 + 1/2*  y^2)) 

plot(times, z, col = "red", ylim = c(-1, 18), type = "l")
lines(times, y, col = "blue")
lines(times, M, col = "green")
grid()

使用此代码可以更快捷地直接计算 R 中的M

library(deSolve)

deriv <- function(t, state, parameters){
  with(as.list(c(state, parameters)),{

    M <- sqrt(1/3 * (1/2 * dy^2 + 1/2 * y^2))
    dz <- M*z # dz/dt
    ddy <-  -3* M * dy -  y # ddy/dt

    list(c(dy, ddy, dz), M = M)

  })
}

state <- c(y = 1,
           dy = -0.1,
       z = 1)

times <- seq(0, 100, length.out = 10001)

sol <- ode(func = deriv, y = state, times = times, parms = NULL)

## save to file

write.csv2(sol,file = "path_to_folder/R_ODE.csv")

## plot

matplot(sol[,"time"], sol[,c("y", "z", "M")], type = "l")
grid()

enter image description here