本文介绍了如何在python中模拟偏向硬币的翻转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在无偏硬币投掷中,H或T发生50%.
In unbiased coin flip H or T occurs 50% of times.
但是我想模拟一个硬币,该硬币的H的概率为'p',而T的概率为'(1-p)'.
But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.
类似这样的东西:
def flip(p):
'''this function return H with probability p'''
# do something
return result
>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
推荐答案
random.random()
返回范围为[0,1)的均匀分布的伪随机浮点数.此数字小于范围为[0,1)且概率为p
的给定数字p
.因此:
random.random()
returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given number p
in the range [0,1) with probability p
. Thus:
def flip(p):
return 'H' if random.random() < p else 'T'
一些实验:
>>> N = 100
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999 # Approximately 20% of the coins are heads
>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999 # Better approximation
这篇关于如何在python中模拟偏向硬币的翻转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!