Tatiana
Tatiana

Reputation: 59

Biased coin flipping?

What is the simplest (does not have to be fastest) way to do a biased random choice between True and False in Python? By "biased", I mean where either True or False is more probable based on a probability I set.

Upvotes: 2

Views: 2243

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881497

It's pretty easy and fast:

import random

def biased_flip(prob_true=0.5):
    return random.random() < prob_true

Of course if you just call biased_flip() you'll get True and False with 50% probability each, but e.g biased_flip(0.8) will give you about eight Trues for each False in the long run.

Upvotes: 9

Related Questions