如何模拟有偏硬币的翻转? [英] How do I simulate flip of biased coin?
本文介绍了如何模拟有偏硬币的翻转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在无偏硬币翻转中,H 或 T 发生的次数为 50%.
但我想模拟硬币,它给 H 的概率为 'p',T 的概率为 '(1-p)'.
像这样:
def 翻转(p):'''这个函数以概率p返回H'''# 做一点事返回结果>>[在 xrange(10) 中为 i 翻转 (0.8)][H,H,T,H,H,H,T,H,H,H]
解决方案
random.random()
返回一个 均匀分布 范围内的伪随机浮点数 [0, 1).该数字小于范围 [0,1) 中的给定数字 p
,概率为 p
.因此:
def 翻转(p):如果 random.random() <返回 'H'其他'T'
一些实验:
<预><代码>>>>N = 100>>>翻转 = [翻转(0.2)对于 xrange(N)中的 i]>>>浮动(翻转.计数('H'))/N0.17999999999999999 # 大约 20% 的硬币是正面>>>N = 10000>>>翻转 = [翻转(0.2)对于 xrange(N)中的 i]>>>浮动(翻转.计数('H'))/N0.20549999999999999 # 更好的近似In unbiased coin flip H or T occurs 50% of times.
But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.
something like this:
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()
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'
Some experiments:
>>> 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
这篇关于如何模拟有偏硬币的翻转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文