[Tutor] What's the best way to model an unfair coin?

Alan Gauld alan.gauld at btinternet.com
Sun Oct 24 14:18:52 CEST 2010

"Richard D. Moores" <rdmoores at gmail.com> wrote

> 'H's and 'T's. If you want the coin to have the probability of a 
> head
> to be 6/11,
> ['H', 'H', 'H', 'H', 'H', 'H', 'T', 'T', 'T', 'T', 'T']
> is the list to use. Use random.choice on the list, for a 6/11 heads
> probability.

That will work but as you say is not very general.
You could write a function that takers the desired probablity
as an input and returns a result based on that.

The simplest way its to generate a random number between
0 and 1 and compare to the required probability expressed
as a decimal fraction.

In pseudo code:

def coinToss(prob = 0.5):
    rand = random()
    if rand >= prob: return True
    else: return False

print "Heads" if coinToss(6/11) else "Tails"

> Am I missing something that's already there in Python 2.6 or 3.1 
> (the
> 2 I have)?

There may well be functions in some of the modules that do it but
the approach above suffices for most applications.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list