R 多变量函数的数值积分

R 多变量函数的数值积分,r,function,plot,numeric,numerical-integration,R,Function,Plot,Numeric,Numerical Integration,嗨,我一直在学习函数的数值积分。我有这个功能: Nd_f <- function(a,t) { theta(t-a)*exp(-l*(1-exp(-a))) } 我得到以下错误: 积分错误(Nd_θ,下限=0,上限=s,t=s): 函数的求值给出了错误长度的结果 我不明白我是否能计算出t的所有值,为什么我不能画出来 l=0.025,v=0.001和 theta <- function(t) { exp(-v*t) } theta我假设theta=exp和l=r=1,因此: N

嗨,我一直在学习函数的数值积分。我有这个功能:

Nd_f <- function(a,t) {
theta(t-a)*exp(-l*(1-exp(-a))) }  
我得到以下错误:

积分错误(Nd_θ,下限=0,上限=s,t=s): 函数的求值给出了错误长度的结果

我不明白我是否能计算出t的所有值,为什么我不能画出来

l=0.025,v=0.001和

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

theta我假设
theta=exp
l=r=1
,因此:

Nd_f <- function(a,t) exp(t-a)*exp(-(1-exp(-r*a)))
但是
集成
不是。您只允许为
lower
upper
传递标量,因此,如果执行以下操作,则没有问题:

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)`
  }
有R经验的人会建议将
for
循环替换为
*应用
系列功能(阅读
?sapply
查看此系列):

使用矢量化函数,可以生成所需的绘图:

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

我假设θ=exp
l=r=1
,因此:

Nd_f <- function(a,t) exp(t-a)*exp(-(1-exp(-r*a)))
但是
集成
不是。您只允许为
lower
upper
传递标量,因此,如果执行以下操作,则没有问题:

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)`
  }
有R经验的人会建议将
for
循环替换为
*应用
系列功能(阅读
?sapply
查看此系列):

使用矢量化函数,可以生成所需的绘图:

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

您不能使用
矢量化
矢量化(Nd)(1:2)#[1]1.273614 4.276839
这是经验。@akrun这很有帮助,特别是对于多变量参数集成。谢谢您不能使用
Vectorize
Vectorize(Nd)(1:2)#[1]1.273614 4.276839
这是经验使然。@akrun这很有帮助,特别是对于多变量参数集成。谢谢
plot(Nd_vectorized_for(1:50), log = "y")