Why is my double integral is R not working

二次信任 提交于 2019-12-31 03:55:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!