问题
Consider the following Matlab code to approximate integrals using simulation.
function f
numSim = 1000000;
points = rand(numSim,1);
r3 = mean(feval('func3', points));
points1 = rand(numSim,1);
r8 = mean(feval('func8', points, points1));
disp([r3, r8,]);
end %f
%%%%%%%%%% Nested funcitons %%%%%%%%%%%%
function y = func3(x)
y = exp(exp(x));
end %func3
function z = func8(x,y)
z = exp((x+y).^2);
end %func8
What I've tried in R
f <- function (func3,func8){
numSim <- 1000000
points <- runif(numSim)
r3 <- mean(evaluate(points, func3))
points1 <- runif(numSim)
r8 <- mean(evaluate( points1,func8))
newList<-list(r3,r8)
return(newList)
}
# Nested functions
func3<-function(x) {
func3 <- exp(exp(x))
return(func3)
}
func8 <- function(x,y) {
func8<-exp((x+y)^2)
return(func8)
}
The first problem was a warning message:
In mean.default(evaluate(points,function)) : argument is not numeric or logical:returning NA
I added r3 <- mean(evaluate(points, func3),na.rm=TRUE)
and when I type r3 the output is [1] NA,
why is it not working correctly?
Additionally, there was a comment about -Nested functions-, I don't understand how to do that in R.
回答1:
This appears to work:
f <- function (func3,func8){
numSim <- 1000000
vals <- runif(numSim) ## changed the name: 'points' is a built-in function
r3 <- mean(sapply(vals, func3))
vals2 <- runif(numSim)
## use mapply() to evaluate over multiple parameter vectors
r8 <- mean(mapply(func8, vals, vals2))
newList <- list(r3,r8)
return(newList)
}
I simplified the function definitions.
func3 <- function(x) {
return(exp(exp(x)))
}
func8 <- function(x,y) {
return(exp((x+y)^2))
}
Try it out:
f(func3,func8)
I have no idea if this is correct, but I think it's a correct translation of your MATLAB code. Note that the implementation could be much faster by using vectorization: replace the sapply()
and mapply()
with mean(func3(vals))
and mean(func8(vals,vals2))
respectively (this only works if the functions to be evaluated are themselves appropriately vectorized, which they are in this case).
来源:https://stackoverflow.com/questions/55427848/code-to-evaluate-an-integral-translating-from-matlab-to-r