rkMethod() # returns the names of all available methods
rkMethod("rk45dp7") # parameters of the Dormand-Prince 5(4) method
rkMethod("ode45") # an alias for the same method
func <- function(t, x, parms) {
with(as.list(c(parms, x)),{
dP <- a * P - b * C * P
dC <- b * P * C - c * C
res <- c(dP, dC)
list(res)
})
}
times <- seq(0, 200, length = 101)
parms <- c(a = 0.1, b = 0.1, c = 0.1)
x <- c(P = 2, C = 1)
ode(x, times, func, parms, method = rkMethod("rk4"))
ode(x, times, func, parms, method = "ode45")
o0 <- ode(x, times, func, parms, method = "lsoda")
o1 <- ode(x, times, func, parms, method = rkMethod("rk45dp7"))
## disable dense-output interpolation
## and use Neville-Aitken polynomials only
o2 <- ode(x, times, func, parms,
method = rkMethod("rk45dp7", densetype = NULL, nknots=5))
## show differences between methods
par(mfrow=c(3,1))
matplot(o1[,1], o1[,-1], type="l", xlab="Time", main="State Variables")
matplot(o1[,1], o2[,-1], type="p", pch=16, add=TRUE)
matplot(o0[,1], o1[,-1]-o0[,-1], type="l", lty="solid", xlab="Time",
main="Difference: rk45dp7 - lsoda")
matplot(o1[,1], o2[,-1]-o1[,-1], type="l", lty="dashed", xlab="Time",
main="difference: Neville-Aitken - Dense Output")
abline(h=0, col="grey")
## disable interpolation completely
## and integrate explicitly between external time steps
o3 <- ode(x, times, func, parms,
method = rkMethod("rk45dp7", densetype = NULL, nknots = 0))
## define and use a new rk method
ode(x, times, func, parms,
method = rkMethod(ID = "midpoint",
varstep = FALSE,
A = c(0, 1/2),
b1 = c(0, 1),
c = c(0, 1/2),
stage = 2,
Qerr = 1
)
)
## compare method diagnostics
times <- seq(0, 200, length = 10)
o1 <- ode(x, times, func, parms, method = rkMethod("rk45ck"))
o1b <- ode(x, times, func, parms, method = rkMethod("rk78dp"))
diagnostics(o1)
diagnostics(o1b)
Run the code above in your browser using DataLab