问题
I folloed this post here double integral in R and switched the function and limits to match below but it's not working.
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
回答1:
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.
来源:https://stackoverflow.com/questions/45471499/why-is-my-double-integral-is-r-not-working