【问题标题】:How to pass vector to integrate function如何将向量传递给积分函数
【发布时间】:2012-08-21 15:36:19
【问题描述】:

我想集成一个函数fun_integrate,它有一个向量vec作为输入参数:

fun_integrate <- function(x, vec) { 
  y <- sum(x > vec)
  dnorm(x) + y
}

#Works like a charm
fun_integrate(0, rnorm(100))

integrate(fun_integrate, upper = 3, lower = -3, vec = rnorm(100))
300.9973 with absolute error < 9.3e-07
Warning message:
  In x > vec :
  longer object length is not a multiple of shorter object length

据我所知,问题如下:integrate 调用 fun_integrate 以获得基于 upperlower 计算的 x 向量。这个向量化调用似乎不适用于作为附加参数传递的另一个向量。我想要的是integrate 为每个x 调用fun_integrate,它在内部计算并将单个x 与向量vec 进行比较,我很确定我上面的代码不会那样做。

我知道我可以自己实现一个集成例程,即计算 lowerupper 之间的节点并分别评估每个节点上的函数。但这不是我的首选解决方案。

还要注意我检查了Vectorize,但这似乎适用于另一个问题,即该函数不接受x 的向量。我的问题是我想要一个额外的向量作为参数。

【问题讨论】:

    标签: r


    【解决方案1】:
    integrate(Vectorize(fun_integrate,vectorize.args='x'), upper = 3, lower = -3, vec = rnorm(100),subdivisions=10000)
    
    304.2768 with absolute error < 0.013
    
    
    #testing with an easier function
    test<-function(x,y) {
      sum(x-y)
    }
    
    test(1,c(0,0))
    [1] 2
    
    test(1:5,c(0,0))
    [1] 15
    Warning message:
    In x - y : 
    longer object length is not a multiple of shorter object length
    
    Vectorize(test,vectorize.args='x')(1:5,c(0,0))
    [1]  2  4  6  8 10
    
    #with y=c(0,0) this is f(x)=2x and the integral easy to solve
    integrate(Vectorize(test,vectorize.args='x'),1,2,y=c(0,0))
    3 with absolute error < 3.3e-14 #which is correct
    

    【讨论】:

    • 我想说:好点子。也许我们中的一个人应该写一个快速梯形版本,看看答案是接近 300 还是 6400 但你去改变了一切! :-) 。你有没有做过类似的事情来验证这个版本是否正确集成?
    • 所以 Vectorize 确实是答案...非常感谢从我这边检查过 ;-) 无论如何,非常感谢!
    【解决方案2】:

    罗兰的回答看起来不错。只是想指出是 sum ,而不是 integrate 正在抛出警告消息。

    Rgames> xf <- 1:10
    Rgames> vf <- 4:20
    Rgames> sum(xf>vf)
    [1] 0
    Warning message:
    In xf > vf :
     longer object length is not a multiple of shorter object length
    

    您得到的答案不是正确值这一事实表明 integrate 没有将您期望的 x 向量发送到您的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多