Flip a weighted coin

I am looking for a function/package that will let me flip a weighted coin in Julia, where I can specify the weight. e.g. some adjustable probability p, that determines the probability of heads.

I found the bitrand function in the Random package but to the best of my knowledge this does not have the option to specify a weight.
Does anyone know if there’s a package/function that can do this?
Thanks

Maybe something like this:

julia> coin(w = 0.5) = rand() < w;

julia> coin()
false

julia> coin()
true
2 Likes

or using Bernoulli distribution from Distributions.jl package. The benefit is that it will be easier to simulate multiple draws.

julia> using Distributions

julia> coin = Bernoulli(0.3)
Bernoulli{Float64}(p=0.3)

julia> rand(coin)
0

julia> rand(coin, 10)
10-element Array{Int64,1}:
 0
 0
 0
 0
 0
 0
 0
 0
 1
 1
3 Likes

Thanks, this might work, but actually what I was looking to do was flip multiple coints with different weights, are there modifications of this that would work? I suppose that would need a new distribution every time so it might not be optimal.

Thanks, I think that this is an elegant solution. In this case if I wanted to use a vector of weights, w, I could just call it as coin.(w) and then flip multiple coins with weights corresponding to entries in w, correct?

Yea, but you can do that with the Distributions example too:

julia> coins = Bernoulli.([0.2, 0.5, 0.7]) # 3 coins with different weights
3-element Array{Bernoulli{Float64},1}:
 Bernoulli{Float64}(p=0.2)
 Bernoulli{Float64}(p=0.5)
 Bernoulli{Float64}(p=0.7)

julia> rand.(coins) # flip the set of coins
3-element BitArray{1}:
 0
 1
 1
7 Likes