Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R – which of these functions is giving the correct value of the integrals?

I am trying to compute this integral in R:

enter image description here

I found three functions which can be used for this and they are all giving me different results. Here is the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

integrand <- function(x){
  r <- 1/x
  return(r)
}

First is the option from base R:

integrate(integrand,-Inf, Inf)

Giving the result:

0 with absolute error < 0

The second is from the pracma package:

quadinf(integrand, -Inf, Inf)

Giving this output:

$Q
[1] -106.227

$relerr
[1] 108.0135

$niter
[1] 7

And the last one is from the cubature package:

cubintegrate(integrand, -Inf, Inf)

Which gives the following result:

$integral
[1] Inf

$error
[1] NaN

$neval
[1] 15

$returnCode
[1] 0

So then, which one of these is correct and which should I trust? Is it 0, infinity, or -106.227? Why are they all different in the first place?

>Solution :

1/x isn’t integrable in [-Inf,Inf] range because it’s infinite for x = 0.

On an integrable range, results are similar:

integrate(\(x) 1/x,1,2)
#0.6931472 with absolute error < 7.7e-15

pracma::quadinf( \(x) 1/x,1,2)
#$Q
#[1] 0.6931472

#$relerr
#[1] 7.993606e-15

#$niter
#[1] 4

Note that integral of 1/x in ]0,Inf] range is log(x):

log(2)-log(1)
#[1] 0.6931472

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading