Choosing a binary value with a certain probability (Biased random generator)

I want to determine a random binary variable according to its probability. So let’s say that I have a binary variable with a probability of 70%, so I want it to become 1 with the probability of 70% and zero with a probability of 30%. How can I do it in Julia? Is there any function for that?

1 Like

If you want exactly one binary variable with 70%/30% probabilities, then you can do something like this

rand() < 0.7 ? 1 : 0

In more general scenario, you can use Distributions package

d = Categorical([0.3, 0.7])
rand(d, 100) .- 1

-1 because Categorical distributions produces 1, 2, 3, 4...

3 Likes

Many thanks!

The more succinct way to do this would be to use the Bernoulli distribution:

using Distributions

dist = Bernoulli(0.7)
rand(dist)
2 Likes

That’s very concise! Thanks!

1 Like