In unbiased coin flip H or T occurs 50% of times.
But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.
something like this:
def flip(p):
'''this function return H with probability p'''
# do something
return result
>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
random.random()
returns a uniformly distributed pseudo-random floating point number in the range [0, 1). This number is less than a given numberp
in the range [0,1) with probabilityp
. Thus:Some experiments:
How about:
That returns a boolean which you can then use to choose H or T (or choose between any two values) you want. You could also include the choice in the method:
but it'd be less generally useful that way.
One can sample from the
X ~ Bernoulli(p)
distributionnsamples
times usingsympy
too:Return
'H'
or'T'
instead usingDo you want the "bias" to be based in symmetric distribuition? Or maybe exponential distribution? Gaussian anyone?
Well, here are all the methods, extracted from random documentation itself.
First, an example of triangular distribution:
Right now probability of Head is 75% and tails is 25% (0,1,2 are all Heads and only 3 is Tails) . By using random.randint() you could have any probability of bias while still maintaining randomness.