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

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post VK Javascript 15 05-02-2010 03:43 PM dpi VHDL 4 03-26-2010 10:31 AM globalrev Python 4 04-20-2008 08:12 AM ANM Java 2 03-07-2004 07:18 AM mescaline C++ 4 09-10-2003 09:01 PM

Advertisments