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

Lie Ryan lie.1296 at gmail.com
Sun Oct 24 17:05:24 CEST 2010


On 10/25/10 02:46, Jose Amoreira wrote:
> On Sunday, October 24, 2010 01:18:52 pm Alan Gauld wrote:
> 
>> 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"
>>
> 
> The only problem with this snippet is integer division: 6/11=0, at least in 
> Python 2.6, so that the final line will always print "Heads".
> 
> But wait! This is pseudo code! Ah, OK. Then 6/11=0.545454..., and Alan was 
> right (as usual).

Except for the missing import (which is traditionally omitted in mailing
list discussions when the context makes it clear), Alan's snippet is
correct in Python 3, which defaults to real division.

Though, I'd probably writes it differently:

def coinToss(prob = 0.5):
    rand = random()
    return rand >= prob

or even:

def coinToss(prob = 0.5):
    return random() >= prob



More information about the Tutor mailing list