0

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ArchieTiger
  • 2,083
  • 8
  • 30
  • 45

2 Answers2

3

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})
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

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.

SmearingMap
  • 320
  • 1
  • 11