Christian Staudt Christian Staudt - 8 days ago 6
Python Question

Efficiently generating a large array of biased coin flips

I am looking for a high-performance Python solution to the following problem:


Flip a biased coin n times so that the probability of heads (=1) is
equal to a given probability p. n is in the millions.


The naive Python implementation is obvious, but I suspect there can be a very efficient
numpy
-based solution.

Answer

You are looking for the NumPy built-in np.random.choice -

np.random.choice([1,0],n,p=[p,1-p])

Let's verify -

In [120]: p = 0.8

In [121]: n = 100000

In [122]: (np.random.choice([1,0],n,p=[p,1-p])==1).mean()
Out[122]: 0.80003999999999997

Looks pretty efficient too -

In [123]: %timeit np.random.choice([1,0],n,p=[p,1-p])
100 loops, best of 3: 4 ms per loop
Comments