Integration in R with integrate function

此生再无相见时 提交于 2020-01-16 17:03:23

问题


library(pbivnorm)

rho <- 0.5
f1 <- function(x, y) {
  pbivnorm(log(x)-10, log(y)-10, rho)*(exp(-(log(x)-10)^2/2)/(sqrt(2*pi)*x))*(exp(-(log(y)-10)^2/2)/(sqrt(2*pi)*y))
}
integration1 <- round(integrate(function(y) {
  sapply(y, function(y) {
    integrate(function(x) f1(x,y), 0, Inf, rel.tol = 1e-12)$value
  })
}, 0, Inf, rel.tol = 1e-12)$value, 10)

This integration should be around 0.3, but R gives 0. Could anyone point out the problem? What is the best function for integral in R? Many thanks.


回答1:


Package cubature can solve the problem giving the expected result. The function must be rewritten as a one argument function, and the values for x and y set in the function body.

library(cubature)

f2 <- function(X) {
  x <- X[1]
  y <- X[2]
  pbivnorm(log(x)-10, log(y)-10, rho)*(exp(-(log(x)-10)^2/2)/(sqrt(2*pi)*x))*(exp(-(log(y)-10)^2/2)/(sqrt(2*pi)*y))
}

hcubature(f2, c(0, 0), c(Inf, Inf))
#$integral
#[1] 0.2902153
#
#$error
#[1] 2.863613e-06
#
#$functionEvaluations
#[1] 7599
#
#$returnCode
#[1] 0

Edit.

Following the OP's second comment, here is the integral computed with hcubature

f3 <- function(x) {
  pnorm(log(x)-10.2)*(exp(-(log(x)-10)^2/2)/(sqrt(2*pi)*x)) 
} 

hcubature(f3, lowerLimit = 0, upperLimit = Inf, tol = 1e-12)$integral 
#[1] 0.4437685


来源:https://stackoverflow.com/questions/59433924/integration-in-r-with-integrate-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!