random number generation

Raymond Hettinger python at rcn.com
Mon Aug 16 21:10:27 EDT 2010


On Aug 16, 5:37 pm, Jah_Alarm <jah.al... at gmail.com> wrote:
> hi,
>
> I need to generate a binary array with a specified average proportion
> of 1s (e.g. [1 0 0 0
>
> 0 1 0 0] has this proportion = 25%). In Matlab I run something like
> random(m,n)<p where p is the value
>
> between 0 and 1. I'm trying to use random.randint(0,2,size=[m,n]), but
> I don't understand how to specify this proportion p.

Try this:

>>> from random import random
>>> [1 if random() < 0.25 else 0 for i in range(20)]
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]


Raymond



More information about the Python-list mailing list