'How to generate random binary numbers 0 or 1 with length of N and with option to control the probability of having 0 or 1?

I want to generate random binary numbers (0 or 1) having N length size. The tricky part is that, It should be able to control the probability of having either more 1 or 0. For example, I want total 100 random numbers with 0 having probability of 40% and 1 having probability of 60%. Please help.



Solution 1:[1]

A general solution for controlling this distribution is as follows:

First generate a uniform random number between 0-100 (or 0-1000 for more control, i.e if you need 60.1% chance for a number)

Then if the number is below or equal to 60, assign 1, now you have a 60% chance to assign 1.

I hope this helps, I think you will figure it out.

Solution 2:[2]

You can always store the count of 0s and 1s. Here since you need a total of 100 random numbers with 0 having the probability of 40% and 1 having the probability of 60% so lets initialize count_0=40, count_1=60, total_count=100. Now you can generate a random number between 0 and 100.

Let us assume the first randomly generated number happens to be 35. Since 35 is less than 40 so first result happens to be 0. Decrement count_0. Decrement total_count. Now, for the next random no pick a randomly generated number between 0 and 99(total_count). This time if the randomly generated number is less than or equal to count_0 ( which equals 39 ) you set the result to be 0 else 1.

Follow this process for 100 iterations to generate 100 random 0s and 1s. This approach uses no extra space and O(n) time complexity where n is the number of 0s and 1s to be generated.

Solution 3:[3]

In Python:

prob = 0.6 #p = prob of having 1
n_samples = np.random.choice([0,1], size=N, p=[prob, 1-prob]) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GustavD
Solution 2 Srishti Ahuja
Solution 3 Andrea Rubeis