user9802913
user9802913

Reputation: 245

Loop with random increment

Consider the following code (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

I am having problems translating function counter = ross_fpt_uniform into R

It confuses me how I should treat the counter because here counter = counter + 1; seems like it's a variable. Is it a function or a variable and how do I write it in R?

My current r code is as follows:

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

Upvotes: 0

Views: 176

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226087

All you're missing is a return(counter) statement.

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

Try it out:

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

enter image description here

Upvotes: 1

Related Questions