0

Consider the Poisson distribution x1, x2, ... ~ pois(1) with lambda=1. I want to write a function that receives a number as input (consider it a) and gives us as output the smallest n (minimum n) which is true for sum(xi)>=a, i=1:n. I think using a while loop could be fine for this situation (but I am not sure that it's the best way). Perhaps it can be done using other loops like for loop. I do not know how to handle this situation containing a Poisson distribution in R?

Edward
  • 10,360
  • 2
  • 11
  • 26
Rojer
  • 335
  • 2
  • 9

1 Answers1

2

A while loop is simple enough to code. It accumulates the values of rpois in s for sum while s < a, counting the iterations in n.

minpois <- function(a){
  n <- 0L
  s <- 0L
  while(s < a) {
    n <- n + 1L
    s <- s + rpois(1L, lambda = 1)
  }
  n
}

set.seed(2020)
minpois(10)
#[1] 12
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you for your code. I have a question. Why have you used 0L and 1L? Why not 0 and 1? If we write n<-0, s<-0, n<-n+1 and s<-s+rpois(1,lambda=1) does it work? What is letter L in your code? @RuiBarradas – Rojer Jun 13 '20 at 07:21
  • @vahid It works without the `L` but since the numbers are integers, I use it. See [the R language definition](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Constants) and [this SO post](https://stackoverflow.com/questions/24350733/why-would-r-use-the-l-suffix-to-denote-an-integer). – Rui Barradas Jun 13 '20 at 07:28
  • What is 1L in rpois(1L, lambda = 1)? Why did you put this argument equal to 1L? How did you find it? – Rojer Jun 13 '20 at 07:32
  • @vahid The loop generates 1 random variable at a time, see `help('rpois')`. – Rui Barradas Jun 13 '20 at 07:34
  • Thank you @RuiBarradas. In your comment, when you said "It works without the L but since the numbers are integers", I have a question regarding "the numbers are integers". Does rpois(n,lambda) always generate integer values? – Rojer Jun 13 '20 at 07:46
  • @vahid Yes, it does. – Rui Barradas Jun 13 '20 at 12:00