-3

Consider the following code in r to generate value of a binomial random variable.

Binomial<-function(n,p,ns)
{
  S <- rep(ns)
  for (i in 1:ns)
  {
    k <-0
    produ<-runif(1)
    while (produ >=(1-p)^n)
    {
      produ <- produ*runif(1)
      k <-k+1
    }
    S[i] <- k
  }
  return(S)
}

Is it correct?

If not, why not?

If yes, can be improved somehow?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user9802913
  • 245
  • 4
  • 20
  • @akrun returns 5 – user9802913 Apr 05 '19 at 01:51
  • @akrun no, if you change it to `ns=10` for example, returns 10 values – user9802913 Apr 05 '19 at 01:53
  • @akrun I don't understand your comment, is my code wrong? – user9802913 Apr 05 '19 at 01:56
  • I don't understand what you're trying to do here. You should provide some context. What are the key requirements of your code? Why not use `rbinom` (as pointed out by @demarsylvain)? This seems to be some form of inverse transform sampling algorithm. Why this particular algorithm? These are critical details you need to provide if you ask fairly broad questions such as *"can [it] be improved somehow"*. Your code also seems to include some odd bits. For example, `rep(ns)` will just return `ns` for a scalar `ns`. What were you trying to do? – Maurits Evers Apr 05 '19 at 06:22
  • I don't know what you mean by "easy code". Easy in what sense? I would say that *good* code is easy to understand, *especially* for a beginner. Good R code also means utilising the strength of R and its vectorised operations. That's not something you're doing at the moment. Dynamically growing a vector (`S` in your example) is a really inefficient way to create an object in R. What I was trying to say in my comment above is that you need to provide context! For example, why sample from a binomial distribution through inverse transform sampling? There are more efficient ways to do that. – Maurits Evers Apr 06 '19 at 03:47

1 Answers1

1

There is a function rbinom() that doing the same. If you build this function for practising, I have a comment for you:

  • you should consider values that could break your function. For instance, I tried to run it with p = 1, and it didn't return a result. This should be fixed.

  • add comments in your function to give definition of the parameters

    Binomial <- function(n, p, ns){
    # n is ....
    # p is the probably of the event
    # ns is ...
    
demarsylvain
  • 2,103
  • 2
  • 14
  • 33