-6

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.

3 Answers3

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.

GustavD
  • 136
  • 4
  • I did not get 60.1% chance. It still has around ±10-20% of deviation. Any solution? – Liril Silvi Aug 05 '21 at 05:50
  • Well, if you flip a coin 10 times most of the time you won't get exactly 5 heads and 5 tails. Maybe you asked your original question wrong. If you need exactly a certain number of 1's and 0's, I think you want to create an array with exactly the number of elements you want, and then insert those elements at random positions in a new array. – GustavD Aug 05 '21 at 08:51
  • I made an array of N numbers with 30% 1s and 70% 0s. e.g. [1 1 1 0 0 0 0 0 0 0]. and then used random shuffle function to randomly shuffle the positions of each element. and it produced the results :[0 0 1 0 1 0 0 0 0 0]. Which looks good to me. Thanks. – Liril Silvi Aug 06 '21 at 13:05
0

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.

Srishti Ahuja
  • 181
  • 1
  • 7
0

In Python:

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