Search code examples
randomjuliabinomial-cdfbernoulli-numbers

Julia, function to replicate "rbinom()" in R


I have dug around and googled but not found an example. I'm sure Julia has a powerful function (in base?) to generate random binomial (bernoulli?) "successes" with a given probability. I can't find it or figure out how to do the equivalent to in Julia:

> rbinom(20,1,0.3)
 [1] 1 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0

Thx. J


Solution

  • You can use Distributions and the rand function for this. Any distribution can be passed to rand. To replicate what you want:

    julia> using Distributions
    
    julia> p = Binomial(1, 0.3)   # first arg is number of trials, second is probability of success
    Binomial{Float64}(n=1, p=0.3)
    
    julia> rand(p, 20)
    20-element Array{Int64,1}:
     0
     1
     1
     0
     1
     0
     0
     1
     0
     1
     1
     1
     0
     0
     1
     0
     1
     0
     0
     1