1

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.

clstaudt
  • 21,436
  • 45
  • 156
  • 239
  • 2
    Possible duplicate of [How do I simulate flip of biased coin in python?](http://stackoverflow.com/questions/477237/how-do-i-simulate-flip-of-biased-coin-in-python) – vishes_shell Nov 27 '16 at 08:40
  • Do you have any preference with the distribution? Uniform, binomial, etc.? – Divakar Nov 27 '16 at 08:58

1 Answers1

3

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
Divakar
  • 218,885
  • 19
  • 262
  • 358