**
- 调包解法
**
一阶微分方程:一元以人口增长为例
我们使用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)
红线和黑线是y=f(t)的图像
二.一阶多元线性微分方程组,以The Lorenz Model 为例
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)
~~
~~
欧拉方法 及其改进
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+hf(x,p)
y=0.5*(p+c)}
return (y)
}
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=hf(x+0.5h,y+0.5q)
e=hf(x+0.5h,y+0.5w)
r=hf(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))}
|
请发表评论