Search code examples
rintegral

Why is my double integral is R not working


I folloed this post here double integral in R and switched the function and limits to match below but it's not working.

enter image description here

InnerFunc = function(x) { x + (y^2) }
InnerIntegral = function(z) { sapply(y, 
        function(z) { integrate(InnerFunc, 0, 2)$value }) }
integrate(InnerIntegral, 0, 1)

I get this error:

Error in integrate(InnerFunc, 0, 2) : evaluation of function gave a result of wrong type


Solution

  • Your variables are all out of wack. This should do what you want

    InnerFunc <- function(x, y) { x + (y^2) }
    InnerIntegral <- function(y) { sapply(y, 
      function(z) { integrate(InnerFunc, 0, 2, y=z)$value }) }
    integrate(InnerIntegral, 0, 1)
    # 2.666667 with absolute error < 3e-14
    

    Notice how InnerFunc is now a function of both x and y. Also notice how we apply over the vector passed to InnerIntegral via the y parameter (rather than ignoring the z value passed in). We also pass in the current value of y to InnerFunc.

    Although you typed

    InnerFunc <- function(x, y) { x + (y^2) }
    

    the math you drew looks should really result in

    InnerFunc <- function(x, y) { x * (y^2) }
    

    so I'm not sure what you were really after.