如何在R中求解和绘制微分方程

时间:2014-07-28 17:59:12

标签: r differential-equations calculus

取自可汗学院Sal Khan的讲座https://www.youtube.com/watch?v=oiDvNs15tkE,如果我知道dN / dt = rN(1-(N / K))(逻辑微分方程)

如何求解N并用R?

绘制N = f(t)

由于

1 个答案:

答案 0 :(得分:9)

此逻辑方程具有解析解(例如参见here),因此您可以直接绘制它。另一个选择是使用一个可用的求解器以数字方式求解它(参见here

## Using the `deSolve` package
library(deSolve)

## Time
t <- seq(0, 100, 1)

## Initial population
N0 <- 10

## Parameter values
params <- list(r=0.1, K=1000)

## The logistic equation
fn <- function(t, N, params) with(params, list(r * N * (1 - N / K)))

## Solving and plotin the solution numerically
out <- ode(N0, t, fn, params)
plot(out, lwd=2, main="Logistic equation\nr=0.1, K=1000, N0=10")

## Ploting the analytical solution
with(params, lines(t, K * N0 * exp(r * t) / (K + N0 * (exp(r * t) - 1)), col=2, lwd=2))

enter image description here