Simulating and Calculating Probabilities
Great, you’re nearly there. Now it’s time to put it all together. In this session, you’re going to simulate and calculate probabilities by implementing a program that for one, uses the
random module to generate random numbers and simulates many coin tosses.
One of the key modules that you’ll be using and when you’ll be simulating random events in general is the
random module. You can import
random with the
import keyword, and after that, you can use one of the functions in the
random module, such as
randint() takes two numbers, a starting one and an ending one.
Armed with this handy function from the
random module, you can define a
coin_flip() function. This
coin_flip() function randomly returns
"tails" by using the
0 as the first lower bound to
1 as the upper bound, so you’re only going to get
1 whenever you run this. You’ve got your
if keyword here, and it’s checking whether this expression,
random.randint(0, 1) == 0, whether that evaluates to
False. If it evaluates to
True, then it’s going to return
"heads". If it evaluates to
False, then it’s going to return
So let’s take that a step further and actually simulate this properly. Here you can initialize two variables, a
heads_tally and a
tails_tally, and basically these will serve to count the number of times that
heads turns up or
tails turns up.
Then you can create a huge
for loop of
10_000 iterations, and you can execute the
coin_flip() within an
if clause and checking if it equals
heads. And if it does, then you increment the
heads_tally. And if it doesn’t, then you increment the
And then at the end, you can
print("heads", heads_tally) and
("tails", tails_tally). You’re printing the string
"heads" just so you know what you’re looking at. And over to the left here, you can see one result of the execution is that
heads was slightly more common than
tails. So how about you run this a couple times?
So it could return
0.535444443, something like in that order, anywhere between
1. So the idea with this function, which is called
unfair_coin_flip(), is that you pass in a
and you’ll want a probability of
0.2, say. Okay, so now save this and run this. And as you can see, the probability is nearly
tails is almost at twenty thousand, while heads takes eighty thousand.
07:10 And you simulated many, many, many coin tosses. You calculated the ratio of heads to tails in these simulations. And you wrote another function that allowed you to alter the behavior of the coin, leaning heavily towards tails or heads, depending on what you pass into that function.
Become a Member to join the conversation.