Python - modelling probability

2019-03-20 05:14发布

问题:

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.