多变量函数的数值积分

numerical integration of multivariable functions

您好,我被函数的数值积分困住了。我有这个功能:

Nd_f <- function(a,t) {
theta(t-a)*exp(-l*(1-exp(-a))) }  

在下面定义的另一个函数中使用:

Nd <- function(s) {
integrate(Nd_f, lower = 0, upper = s, t=s)$value }  

其中,theta() 是已知函数。因此,使用这些函数我可以评估 Nd(t)。但是当我尝试使用以下方法绘制它时:

plot(Nd(0:500), log="y")

我收到以下错误:

Error in integrate(Nd_theta, lower = 0, upper = s, t = s) : evaluation of function gave a result of wrong length

我不明白我是否可以针对 t 的所有值对其进行评估,为什么我不能绘制它?

l=0.025,v=0.001 和

theta <- function(t) { exp(-v*t) }

提前致谢!

我假设 theta = expl = r = 1,所以:

Nd_f <- function(a,t) exp(t-a)*exp(-(1-exp(-r*a)))

函数Nd <- function(s) integrate(Nd_f, lower = 0, upper = s, t=s)$value旨在计算积分:

请注意 integrate 不是向量化函数。 一个向量化函数可以接受向量输入,return一个向量。例如,exp函数是向量化的,因为:

exp(1:3)
# [1]  2.718282  7.389056 20.085537

但是integrate不是。您只允许为 lowerupper 传递标量。 因此,如果您这样做没有问题:

Nd(1)
# [1] 1.273614

但是当你这样做时它不起作用:

Nd(1:2)
# [1] 2.286086
# There were 15 or more warnings (use warnings() to see the first 15)
# warnings()
# Warning messages:
# 1: In t - a : longer object length is not a multiple of shorter object length

您需要包装标量函数 Nd 以获得向量化函数。 如果您真的是 R 的新手,您可以使用 for循环:

Nd_vectorized_for <- function(s) {
  result <- numeric(length(s))
  for (i in 1:length(s)) {
    result[i] <- Nd(s[i])
    }
  result  ## or `return(result)`
  }

现在这个函数可以接受向量输入和return一个向量:

Nd_vectorized_for(1:2)
# [1] 1.273614 4.276839

对 R 更有经验的人会建议用 *apply 系列函数替换 for 循环(阅读 ?sapply 以查看此系列):

Nd_vectorized_sapply <- function(s) sapply(s, Nd)

Nd_vectorized_sapply(1:2)
# [1] 1.273614 4.276839

但是 integrate 不是一个便宜的操作,所以 sapply 没有性能提升:

system.time(Nd_vectorized_for(sample(1:10,100000,replace=TRUE)))
#   user  system elapsed 
#  6.256   0.004   6.268 
system.time(Nd_vectorized_sapply(sample(1:10,100000,replace=TRUE)))
#   user  system elapsed 
#  6.200   0.004   6.212 

使用矢量化函数,您可以生成您想要的图:

plot(Nd_vectorized_for(1:50), log = "y")