How can I generate random numbers say between 0 and 1, according to the distribution 20%, 80% i.e.
for i in range(0, 10):
print random.randint(0, 1)
>>> 1 1 0 1 0 1 1 1 1 1
- 20% 0s
- 80% 1s
How can I generate random numbers say between 0 and 1, according to the distribution 20%, 80% i.e.
for i in range(0, 10):
print random.randint(0, 1)
>>> 1 1 0 1 0 1 1 1 1 1
Make use of the fact that booleans are also integers; True
is 1 and False
is 0; the following produces 1
80% of the time, 0
otherwise:
int(random.random() < 0.8)
Demo:
>>> import random
>>> from collections import Counter
>>> Counter(int(random.random() < 0.8) for _ in range(1000))
Counter({1: 798, 0: 202})
One way to handle it:
>>>import random
>>>random.choice(2*[0]+8*[1])
To elaborate, this will select at random from a list containing 2 zeros and 8 ones.