Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary random array with a specific proportion of ones?

What is the efficient(probably vectorized with Matlab terminology) way to generate random number of zeros and ones with a specific proportion? Specially with Numpy?

As my case is special for 1/3, my code is:

import numpy as np  a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3) 

But is there any built-in function that could handle this more effeciently at least for the situation of K/N where K and N are natural numbers?

like image 943
Cupitor Avatar asked Oct 25 '13 18:10

Cupitor


1 Answers

Yet another approach, using np.random.choice:

>>> np.random.choice([0, 1], size=(10,), p=[1./3, 2./3]) array([0, 1, 1, 1, 1, 0, 0, 0, 0, 0]) 
like image 187
Jaime Avatar answered Oct 13 '22 06:10

Jaime