通过时间在 R 中集成一个函数
Integrate a function in R through time
我想针对 t 集成以下函数,下限 = 0,上限 = t。我可以用下面的代码做到这一点,但我的最终目标是为每个 t 获得一个积分值。即使我将 t 设为一个序列而不是一个值,或者如果我尝试使用 sapply,我仍然无法在 t 的每一步获得积分值。
#initialize constants
kap=-0.1527778
alph0<-6
b<-0
po<-0.01
t<-100
gp_st<-integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=t)$value
#try alternate where t is now a sequence
t<-seq(1:100)
gp_st2<-function(h) sapply(h,gp_st) #still gives length of 1
谢谢!
尝试使 gp_st
成为上限的函数,如下所示:
gp_st <- function(h) {
integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=h)$value
}
然后你就可以随意使用sapply了:
t<-seq(1:100)
gp_st2 <- sapply(t, gp_st)
现在 gp_st2
是一个长度为 100 的数值向量。
问题是您正在计算 gp_st 中的积分,而您不想这样做。您想要以下内容:
ff = function(t) {
(1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap)
}
sapply(1:100, function(ul) {
integrate(ff, lower = 0, upper = ul)$value
})
自然有更有效的方法来做到这一点。
我想针对 t 集成以下函数,下限 = 0,上限 = t。我可以用下面的代码做到这一点,但我的最终目标是为每个 t 获得一个积分值。即使我将 t 设为一个序列而不是一个值,或者如果我尝试使用 sapply,我仍然无法在 t 的每一步获得积分值。
#initialize constants
kap=-0.1527778
alph0<-6
b<-0
po<-0.01
t<-100
gp_st<-integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=t)$value
#try alternate where t is now a sequence
t<-seq(1:100)
gp_st2<-function(h) sapply(h,gp_st) #still gives length of 1
谢谢!
尝试使 gp_st
成为上限的函数,如下所示:
gp_st <- function(h) {
integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=h)$value
}
然后你就可以随意使用sapply了:
t<-seq(1:100)
gp_st2 <- sapply(t, gp_st)
现在 gp_st2
是一个长度为 100 的数值向量。
问题是您正在计算 gp_st 中的积分,而您不想这样做。您想要以下内容:
ff = function(t) {
(1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap)
}
sapply(1:100, function(ul) {
integrate(ff, lower = 0, upper = ul)$value
})
自然有更有效的方法来做到这一点。