linamnt
linamnt

Reputation: 1392

Efficient random 0,1 generation of independant probabilities in Python

I have a large array of probabilities that are independent of each other. Is there an efficient way to generate a 0 or 1 based on each of these probabilities other than calling numpy random each time in a loop? I only need the result of one trial each time, but for each of the probabilities.

# current method using np.random.binomial()
n = 1
p = np.random.random(1000) #generating 1000 probabilities

results = np.zeros(1000)
for ix, i in enumerate(p):
    results[ix] = np.random.binomial(n,i,1)

Is there a faster way or function that can take an independant set of probabilities (so not random choice, since the probabilities will not add to 1).

Upvotes: 2

Views: 6262

Answers (2)

scnerd
scnerd

Reputation: 6103

The p parameter to np.random.binomial is allowed to be list-like, and when it is that way, it represents the p value for each sample. Also, when used list-like like this, you don't even need to provide the number of samples you expect in total: you just get one for each value in p.

results = np.random.binomial(n, p)

And some samples to prove this out:

In [1]: np.random.binomial(1, 0.5)
Out[1]: 1

In [2]: np.random.binomial(1, [0.5, 0.5, 0.9])
Out[2]: array([0, 0, 1])

Upvotes: 9

Aechlys
Aechlys

Reputation: 1306

You can try this:

np.where(p > np.random.rand(1000), 1, 0) 

Upvotes: 1

Related Questions