Drawing from a binomial distribution

85 views
Skip to first unread message

Katie Tseng

unread,
Nov 9, 2023, 1:34:00 AM11/9/23
to netlog...@googlegroups.com
Hi everyone!

I am new to NetLogo and am trying to translate the R code below into NetLogo. Is there a similar command to 'rbinom' in NetLogo? I know there is random-poisson, for example, and this post on stack overflow suggests there is/was a random-binomial at some point, but I don't see it available in the NetLogo dictionary. Any help would be much appreciated!

##############
N=500
P0=0.1
Status <- rbinom(N,size=1,prob=P0) ; (number of obs, number of trials, pr of success on each trial)
##############

Thank you,

Katie

Charles Staelin

unread,
Nov 9, 2023, 12:06:38 PM11/9/23
to netlogo-users
Katie,

The stats extension can provide you with the binomial distribution and its cdf.  I'm happy to let someone better versed in probability to correct me, but I believe that to find a random binomial between 0 and n, given the probability p, one can provide a uniform random number between 0 and 1, x, and then find the number of successes, K, for which the probability of 0 to K successes equals x.  Unfortunately, the stats extension does not provide the inverse binomial, but we can calculate it from the binomial cdf.  You can check the following code against what R yields.  I don't have R on this machine, but I'll check when I get a chance.

extensions [stats]

to-report random-binomial [n p]
  let x random-float 1
  report binomial-inverse n x p
end

to-report binomial-inverse [n x p]
  let r 0
  while [stats:binomial-sum-to n r p <= x] [set r r + 1]
  report r
end

Charles

Luka Grgičević

unread,
Jan 5, 2024, 2:29:45 PMJan 5
to netlogo-users
Hi,

You can do it this way as well, without the extension:

; The following two function computes binomial distribution 0, skewed to left 1, skewed to right
to-report CREATE-BINS [n p]
  let bins n-values n [v -> BINOMIAL-COEFFICIENT (n - 1) v * (p ^ v) * ((1 - p) ^ ((n - 1) - v))]
  let total sum bins
  report map [x -> x / total] bins
end

to-report BINOMIAL-COEFFICIENT [n ka]
  ifelse ka = 0
    [ report 1 ]
    [ report (n) * BINOMIAL-COEFFICIENT (n - 1) (ka - 1) / ka ]
end

Best regards,
Luka

Reply all
Reply to author
Forward
0 new messages