Search code examples
rparameter-passingintegral

Passing additional parameters to pracma::integral2


I am using pracma::integral2 to integrate a function that sometimes requires additional parameters, but integral2 seems not to recognise the parameters I supply. Consider these two functions:

fun1 <- function(x, y) exp(-x^2 - y^2)
fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2)

If I then run

integral2(fun1,
      xmin = 0,
      xmax = 1,
      ymin = 0,
      ymax = 1)$Q

I get 0.5577463 as expected. But if I run:

   integral2(fun2,
          xmin = 0,
          xmax = 1,
          ymin = 0,
          ymax = 1,
          a = 1)$Q

I get:

Error in fun(x, y, ...) : argument "a" is missing, with no default 

Trackback shows the following:

  1. fun(x, y, ...)
  2. FUN(X, Y)
  3. .tensor(xmin, xmax, thetaL, thetaR, phiB, phiT, FUN, phiBvar, phiTvar, vectorized = vectorized, singular = singular)
  4. integral2(fun2, xmin = 0, xmax = 1, ymin = 0, ymax = 1, a = 1)

I don't know what .tensor is, but it looks as if its product FUN(X,Y) has lost the ....

What is going wrong here?


Solution

  • a is being matched to the abstol argument of integral2. Just rename a to something else in fun2 as in solution 1 below or else specify abstol explicitly so it does not get confused as in solution 2 below.

    library(pracma)
    
    # solution 1
    fun2aa <- function(x, y, aa) (1 / aa) * exp(-x^2 - y^2)
    integral2(fun2aa,
              xmin = 0,
              xmax = 1,
              ymin = 0,
              ymax = 1,
              aa = 1)$Q
    ## [1] 0.5577463
    
    # solution 2
    fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2) # same as in question
    integral2(fun2,
              xmin = 0,
              xmax = 1,
              ymin = 0,
              ymax = 1,
              abstol = 0, # added
              a = 1)$Q
    ## [1] 0.5577463
    

    Note that if integral2 had put the dot dot dot before abstol then it would not have been a problem. Here integral2a is the same as integral2 except the dot dot dot is placed after ymax.

    # solution 3
    
    fun2 <- function(x, y, a) (1 / a) * exp(-x^2 - y^2) # same as in question
    
    integral2a <- function (fun, xmin, xmax, ymin, ymax, ..., 
      sector = FALSE, reltol = 1e-06, abstol = 0, maxlist = 5000, 
      singular = FALSE, vectorized = TRUE) {}
    body(integral2a) <- body(integral2)
    environment(integral2a) <- environment(integral2)
    
    integral2a(fun2,
              xmin = 0,
              xmax = 1,
              ymin = 0,
              ymax = 1,
              a = 1)$Q
    ## [1] 0.5577463