1

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

Brian Wiley
  • 485
  • 2
  • 11
  • 21

1 Answers1

3

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • hi so the answer should be .6666667, see here https://www.symbolab.com/solver/double-integrals-calculator/%5Cint_%7B0%7D%5E%7B1%7D%5Cint_%7B0%7D%5E%7B2%7Dxy%5E%7B2%7D%20dxdy – Brian Wiley Aug 02 '17 at 23:31
  • I already mentioned in the answer that in your code you put `x + (y^2)` but if you meant `x * (y^2)` then you'd get .666 as expected. – MrFlick Aug 02 '17 at 23:33