Velocity Reviews > random number generation

# random number generation

Jah_Alarm
Guest
Posts: n/a

 08-17-2010
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

Brian Blais
Guest
Posts: n/a

 08-17-2010
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://www.velocityreviews.com/forums/(E-Mail Removed)
http://web.bryant.edu/~bblais
http://bblais.blogspot.com/

Raymond Hettinger
Guest
Posts: n/a

 08-17-2010
On Aug 16, 5:37*pm, Jah_Alarm <(E-Mail Removed)> 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