传递两个或多个向量来集成函数

时间:2016-12-02 00:59:20

标签: r vector integrate

我试图整合这个功能,其中k1& m1是两个输入向量

k_z <- function(z, k1, m1) {
  k_z <- k1 * exp(-z / m1)
}

我改编了this question

的解决方案
integrate(Vectorize(k_z, vectorize.args = "z"), upper = 2, lower = 0, k1 = rnorm(10), m1 = rnorm(10))

但出现以下错误

Error in integrate(Vectorize(k_z, vectorize.args = "z"), upper = 2, lower = 0,  : 
  evaluation of function gave a result of wrong length

我尝试了许多不同的方法无济于事。我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

你的函数k_z不是一个标量点&#39; 函数&#39;,因为它根据集成的需要给定一组参数值不会返回单个值函数(因为它是1对多):让k_z返回如下的单个值,它将起作用:

k_z <- function(z, k1, m1) {
  sum(k1 * exp(-z / m1)) # return a single value, not a vector of multiple values
}

k_z_vec <- Vectorize(k_z, vectorize.args = "z")
integrate(k_z_vec, upper = 2, lower = 0, k1 = rnorm(10), m1 = rnorm(10))
# -7.338221e+14 with absolute error < 1.4e+07

如果要计算具有不同值的多个集成  向量k1和m1,您可以尝试以下方法:

k_z <- function(z, k1, m1) {
  k1 * exp(-z / m1)
}
k1 <- rnorm(10)
m1 <- rnorm(10)
sapply(1:10, function(x) integrate(k_z, upper = 3, lower = -3, k1=k1[x], m1=m1[x]))

            [,1]         [,2]         [,3]         [,4]         [,5]       [,6]         [,7]         [,8]         [,9]         [,10]       
value        -21.4522     4.330284e+40 19.4474      3.900487e+21 9649111978 2.092415e+57 -34.86148    10103.57     -8.232609    46.35694    
abs.error    2.381672e-13 2.705507e+35 2.159095e-13 1.129735e+17 83251.15   1.180714e+49 3.870402e-13 0.0003484398 9.140032e-14 5.942846e-10
subdivisions 1            4            1            3            2          5            1            1            1            1           
message      "OK"         "OK"         "OK"         "OK"         "OK"       "OK"         "OK"         "OK"         "OK"         "OK"        
call         Expression   Expression   Expression   Expression   Expression Expression   Expression   Expression   Expression   Expression