Reputation: 15
I am new to python. I want to write a function which generates a random nxm
binary matrix with each value 0 for probability p.
What I did.
def randbin(M,N,P): # function to generate random binary matrix
mat = (np.random.rand(M,N)>=P).astype(int)
return mat
y = randbin(5,4,0.3)
Every time I print the output, I didn't get the result as per the estimated probability. I don't know what I am doing wrong.
Upvotes: 1
Views: 4276
Reputation: 9891
I don't see the problem with your method... A better way to generate a random matrix of 0s and 1s with a probability P of 0s is to use random.choice
:
def randbin(M,N,P):
return np.random.choice([0, 1], size=(M,N), p=[P, 1-P])
To better understand, have a look at the random.choice
documentation.
Upvotes: 3