我正在寻找一个高性能的 Python 解决方案来解决以下问题:
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.
简单的 Python 实现是显而易见的,但我怀疑可能有一个非常有效的基于 numpy 的解决方案。
最佳答案
您正在寻找 NumPy 内置 np.random.choice
-
np.random.choice([1,0],n,p=[p,1-p])
让我们验证一下 -
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
看起来也相当高效 -
In [123]: %timeit np.random.choice([1,0],n,p=[p,1-p])
100 loops, best of 3: 4 ms per loop
关于python - 有效地生成大量有偏差的抛硬币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827134/