Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement