您的函數k_z不是一個標量點'函數',因爲它不會返回單個值,因爲集成函數需要參數的一組值(因爲它是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
非常感謝您的幫助!它現在有效 – Tung