# random number generation

Discussion in 'Python' started by Jah_Alarm, Aug 17, 2010.

1. ### Jah_AlarmGuest

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.

thanks,

Alex

Jah_Alarm, Aug 17, 2010

2. ### Brian BlaisGuest

On Aug 16, 2010, at 20:37 , Jah_Alarm 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.
>

if you're coming from matlab, then you should use the numpy package
(and you can post questions on the numpy list). In that case, you
can do:

from numpy import *
random.rand(5,7)<0.25

array([[False, True, True, False, False, True, False],
[False, False, False, False, True, False, False],
[ True, False, False, False, False, False, True],
[ True, False, True, False, False, False, False],
[False, False, False, False, False, False, False]], dtype=bool)

just like matlab.

bb

--
Brian Blais

http://web.bryant.edu/~bblais
http://bblais.blogspot.com/

Brian Blais, Aug 17, 2010

3. ### Raymond HettingerGuest

On Aug 16, 5:37 pm, Jah_Alarm <> 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

Raymond Hettinger, Aug 17, 2010