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

问题描述 投票:2回答:1

我想为指数增长求解并绘制一个微分方程,但是我不太了解如何使用deSolve库。我的方程是N = N_0 * e ^(rt),我尝试过的代码是

library(deSolve)

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

## Initial population
N0 <- 2

## Parameter values
r = 1

fn <- function(t, N0, r) with(r, list(N0 * exp(r*t)))

## Solving and ploting 
out <- ode(N0, t, fn, params)
plot(out, lwd=2, main="exp")

但是我希望不是我想要的输出。我要获取的图形如下:

enter image description here

希望您能帮助我。谢谢

r plot differential-equations
1个回答
1
投票

模型函数fn应包含导数,然后由求解器完成积分。一阶增长当然可以通过解析来解决,但是对于更复杂的模型而言,这并不总是可能的。

library(deSolve)

## == derivative ==
fn <- function(t, N, r) {
  # dN/dt = r * N
  list(r * N)
}

r <- 1       # Parameter value
N <- 0:100   # sequence of N
t <- 0       # dummy as the derivative is not time dependent

plot(N, fn(t, N, r)[[1]], type="l")

## == integration ==
t <- seq(0, 5, .1)  # time
N0 <- 2             # initial state

## numerical solver
out <- ode(N0, t, fn, r)
plot(out, lwd=2, main="exp")

## for comparison: analytical integration
lines(t, N0*exp(r*t), lwd=2, lty="dotted", col="red")
© www.soinside.com 2019 - 2024. All rights reserved.