[Numpy-discussion] random number genration

Sturla Molden sturla@molden...
Tue Mar 29 07:56:33 CDT 2011


Den 29.03.2011 11:00, skrev Alex Ter-Sarkissov:
> If I want to generate a string of random bits with equal probability I 
> run
>
> random.randint(0,2,size).
>
> What if I want a specific proportion of bits? In other words, each bit 
> is 1 with probability p<1/2 and 0 with probability q=1-p?

Does this work you?

import numpy as np

def randombits(n, p):
     b = (np.random.rand(n*8).reshape((n,8)) < p).astype(int)
     return (b << range(8)).sum(axis=1).astype(np.uint8)


Sturla




More information about the NumPy-Discussion mailing list