Python - modelling probability

青春壹個敷衍的年華 提交于 2019-12-20 23:48:17

问题


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?


回答1:


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

Looks about right.

As noted in comments, you can shorten your method a bit:

p = 0.40

def generate():
    return 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.



来源:https://stackoverflow.com/questions/16992533/python-modelling-probability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!