评估积分的代码:从Matlab转换为R [英] Code to evaluate an integral: translating from Matlab to R

查看:139
本文介绍了评估积分的代码:从Matlab转换为R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Matlab代码以使用仿真近似积分.

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

我在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:

在mean.default(evaluate(points,function))中: 参数不是数字或逻辑:返回NA

In mean.default(evaluate(points,function)) : argument is not numeric or logical:returning NA

我添加了r3 <- mean(evaluate(points, func3),na.rm=TRUE)

当我键入r3时,输出为[1] NA,

and when I type r3 the output is [1] NA,

为什么不能正常工作?

另外, 关于-嵌套函数-的评论,我不知道如何在R中做到这一点.

Additionally, there was a comment about -Nested functions-, I don't understand how to do that in R.

推荐答案

这似乎有效:

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)
}

我简化了函数定义.

func3 <- function(x) {
  return(exp(exp(x)))
}   
func8 <- function(x,y) {
  return(exp((x+y)^2))
}

尝试一下:

f(func3,func8)

我不知道这是否正确,但是我认为这是MATLAB代码的正确翻译.请注意,通过使用向量化可以更快地实现:用mean(func3(vals))mean(func8(vals,vals2))分别替换sapply()mapply()(这仅在要评估的函数本身被适当地向量化的情况下才有效.情况).

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).

这篇关于评估积分的代码:从Matlab转换为R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆