[Tutor] What's the best way to model an unfair coin?
steve at pearwood.info
Sun Oct 24 14:17:13 CEST 2010
Richard D. Moores wrote:
> What's the best way to model an unfair coin?
Let probability of heads = p, where 0 <= p <= 1
Then probability of tails = 1-p.
if random.random() <= p: print("got heads")
else: print("got tails")
> That's the only way I can think of. But surely there's a better, more
> general solution. What if the probability I want is an irrational
> number, such as 1/e? Sure, I can calculate a fraction that's as close
> to that irrational number as I want, but..
Well, technically speaking all floats in Python are rational numbers,
since they're base-2 floating point numbers. But the difference between
(say) float pi and the true irrational number π is around about
0.0000000000000001, so close enough for most purposes.
More information about the Tutor