以随机增量循环

时间:2019-03-30 18:36:30

标签: r matlab while-loop

考虑以下代码(Matlab)

function counter = ross_fpt_uniform
%ROSS_FPT_UNIFORM generates the first passage time of the sum of uniform
% random variables exceeding level 1.
    s = 0;
    counter = 0;
    while (s <= 1)
        s = s + rand(1,1);
        counter = counter + 1;
    end
end %ross_fpt_uniform

我无法将function counter = ross_fpt_uniform转换为R

这让我感到困惑,我该如何对待counter,因为在这里counter = counter + 1;似乎是一个变量。它是函数还是变量,如何用R编写?

我当前的r代码如下:

counter<-function() {
  s<-0 
  counter<-0 
  while(s<=1){
    s <- s + runif(1) 
    counter <- counter+1
  }
}

1 个答案:

答案 0 :(得分:1)

您所缺少的只是一个return(counter)语句。

counter<-function() {
  s <- 0 
  counter <- 0 
  while(s<=1){
    s <- s + runif(1) 
    counter <- counter+1
  }
  return(counter)
}

尝试一下:

set.seed(101); cc <- replicate(1000,counter())
plot(table(cc))

enter image description here