R语言常微分方程数值解海强作业

**

  1. 调包解法

**
一阶微分方程:一元以人口增长为例
在这里插入图片描述
我们使用R package deSolve ODEs 函数。
A simplified form of the syntax for solving ODEs is: ode(y, times, func, parms, …)
where times holds the times at which output is wanted, y holds the initial conditions, func is the name of the R function that describes the differential equations,andparmscontainsthe parametervalues(oris NULL)
dy/dx.
Ode()的y相当于y(0) times相当与dx,function 相当与ry(1-y/k)

r <- 1
K <- 10
yini <- 2
derivs <- function(t, y, parms) list(r * y * (1-y/K))
library(deSolve)
times <- seq(from = 0, to = 20, by = 0.2)
out <- ode(y = yini, times = times, func = derivs, parms = NULL)
我们换个y(0)=12,输出out2.
r <- 1
K <- 10
yini <- 12
derivs <- function(t, y, parms) list(r * y * (1-y/K))
library(deSolve)
times <- seq(from = 0, to = 20, by = 0.2)
out2 <- ode(y = yini, times = times, func = derivs, parms = NULL)
画出out1,out2.
plot(out, out2, main = “logistic growth”, lwd = 2)

R语言常微分方程数值解海强作业_第1张图片红线和黑线是y=f(t)的图像

二.一阶多元线性微分方程组,以The Lorenz Model 为例
R语言常微分方程数值解海强作业_第2张图片

a <- -8/3
b <- -10
c <- 28
yini <- c(X = 1, Y = 1, Z = 1)
Lorenz <- function (t, y, parms)
{with(as.list(y),{
dX <- aX+YZ
dY <- b*(Y-Z)
dZ<-XY+cY-Z
list(c(dX, dY, dZ))})}
times <- seq(from = 0, to = 100, by = 0.01)
out <- ode(y = yini,times = times, func = Lorenz, parms = NULL)

R语言常微分方程数值解海强作业_第3张图片

~~

  • 自编函数

~~
欧拉方法 及其改进
R语言常微分方程数值解海强作业_第4张图片

Euler<-function
(x,h=0.1,func=f(),inni=c(0,0))
{ y<-inni[2]
for (i in 0:((x-inni[1])/h)) {
x=x+h
y=y+h*f(x,y)}
return (y)
}

adEuler<-function(x,h=0.1,func=f(),inni=c(0,0))
{ y<-inni[2]
for (i in 0:((x-inni[1])/h)) {
p=y+hf(x,y)
x=x+h
c=y+h
f(x,p)
y=0.5*(p+c)}
return (y)
}

在这里插入图片描述
R语言常微分方程数值解海强作业_第5张图片

Runge<-function(x,h=0.1,func=f(),inni=c(0,0))
{ y<-inni[2]
for (i in 0:((x-inni[1])/h)) {
q=hf(x,y)
w=h
f(x+0.5h,y+0.5q)
e=hf(x+0.5h,y+0.5w)
r=h
f(x+0.5h,y+e)
x=x+h
y=y+(1/6)
(q+2w+2e+r)}
return (y)
}

f<-function(x,y){return(y*(1-y**2))}

你可能感兴趣的:(R语言常微分方程数值解海强作业)