Python-建模概率 [英] Python - modelling probability
问题描述
我有一个简单的问题.我需要一种使函数在p%的情况下生成0并在所有其他情况下生成1的函数的方法.我尝试使用random.random()这样操作:
I have a simple problem. I need a way to make a function which generates 0s in p percent cases and 1s in all other cases. I tried doing it with random.random() like this:
p = 0.40
def generate():
x = random.random()
if x < p:
return 0
else:
return 1
但是,这似乎不是一个好方法.还是它?
However, this doesn't seem like a good way. Or it is?
推荐答案
您当前的方法非常好,您可以通过多次尝试进行多次试验来验证这一点.例如,我们期望通过1000000次尝试获得大约600000个True结果:
Your current method is perfectly fine, you can verify this by performing a few trials with a lot of attempts. For example we would expect approximately 600000 True results with 1000000 attempts:
>>> sum(generate() for i in range(1000000))
599042
>>> sum(generate() for i in range(1000000))
599670
>>> sum(generate() for i in range(1000000))
600011
>>> sum(generate() for i in range(1000000))
599960
>>> sum(generate() for i in range(1000000))
600544
看对了.
如评论中所述,您可以稍微缩短方法:
As noted in comments, you can shorten your method a bit:
p = 0.40
def generate():
return random.random() >= p
如果要使用1
和0
而不是True
和False
,则可以使用int(random.random() >= p)
,但这绝对是不必要的.
If you want 1
and 0
instead of True
and False
you can use int(random.random() >= p)
, but this is almost definitely unnecessary.
这篇关于Python-建模概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!