3

Taken from Sal Khan's lecture https://www.youtube.com/watch?v=oiDvNs15tkE of the Khan academy, if I know that dN/dt=rN(1-(N/K)) (the logistic differential equation)

How can I solve for N and plot the N=f(t) with R?

Thanks

ECII
  • 10,297
  • 18
  • 80
  • 121

1 Answers1

9

This logistic equation has an analytical solution (see for example here), so you can plot it directly. Another option is to solve it numerically using one of the available solvers (see 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

alko989
  • 7,688
  • 5
  • 39
  • 62
  • haven't checked, but it's a little surprising that the analytical and numerical solutions are visibly different ... – Ben Bolker Jul 29 '14 at 02:06
  • If you find a problem please let me know (or edit). – alko989 Jul 29 '14 at 02:29
  • 3
    Two problems: (1) you use `Y0` instead of `N0` in your analytical expression. (2) in order for your analytical and numerical solutions to line up, you need to start the ODE solution from t=0 rather than t=1 (e.g. `t <- 0:100`) – Ben Bolker Jul 29 '14 at 03:12