拟合微分方程:如何将一组数据拟合到R中的微分方程

时间:2013-03-27 14:08:28

标签: r differential-equations

使用数据集:

conc <- data.frame(time = c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration = c(170, 122, 74, 45, 28, 17, 10))

我希望将这些数据与下面的微分方程拟合:

dC/dt= -kC

其中C是数据集中的浓度和时间t。这也会得到k的结果。有人能给我一个如何在R中做到这一点的线索吗?感谢。

2 个答案:

答案 0 :(得分:1)

首先使用变量分离来求解微分方程。这给出了log(C)= - k * t + C0。

绘制数据:

plot(log(concentration) ~ time,data=conc)

拟合线性模型:

fit <- lm(log(concentration) ~ time,data=conc)
summary(fit)

# Coefficients:
#               Estimate Std. Error t value Pr(>|t|)    
# (Intercept)   5.299355   0.009787   541.4 4.08e-13 ***
#   time       -0.992208   0.005426  -182.9 9.28e-11 ***
#   ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 
# 
# Residual standard error: 0.01388 on 5 degrees of freedom
# Multiple R-squared: 0.9999,  Adjusted R-squared: 0.9998 
# F-statistic: 3.344e+04 on 1 and 5 DF,  p-value: 9.281e-11 

绘制预测值:

lines(predict(fit)~conc$time)

提取k:

k <- -coef(fit)[2]
#0.9922081

enter image description here

答案 1 :(得分:0)

这可能是一个解决方案:

    require('deSolve')
conc <- data.frame(time <- c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration <- c(170, 122, 74, 45, 28, 17, 10))

##"Model" with differential equation
model <- function(t, C, k){
  list(-k * C)
}

##Cost function with sum of squared residuals:
cost <- function(k){
  c.start <- 170
  out <- lsoda(c(C=c.start), conc$time, model, k)
  c <- sum( (conc$concentration - out[,"C"])^2)       
  c
}

##Initial value for k
k <- 3
##  Use some optimization procedure
opt <- optim(k, cost, method="Brent", lower=0, upper=10)

k.fitted <- opt$par

也许这有点天真,因为使用lsoda似乎有点过分仅用一个微分方程进行计算......但它肯定会优化你的k。 您可能想要检查C的起始值以进行集成,我在此处将其设置为170,您是否有t = 0的值?

相关问题