Simulation of a coin toss in R

In Wednesday’s class I showed how easy it was to generate a simple coin-tossing experiment in R.

I introduced the function sample() and I asked the following question:

“What is your expected p&l after tossing a fair coin 1000 times, if when it lands heads,
you receive a dollar and when it lands tails, you pay me a dollar?”

We can easily derived the expected value of this game by using the fact that the coin toss is a binary outcome with equal probability. E(pnl) = 1 * p + -1 * (1-p) = 0

But where’s the fun in that! Rather, we decided to simulate such an experiment.

Programmatically, we can toss a single coin 1000 times and observe the outcome.
Conceptually, we will generate a bucket with 2 numbers (-1 and 1). Every time we pull a value out of that bucket (toss the coin), we will need to record the value and then replace it. If we don’t replace the number, we won’t have any numbers left after 2 coin tosses. Here’s the code that will do that:

 sequenceOfCoinTosses <- sample(c(-1,1), 1000, replace = TRUE)

This is what the outcome looks like:

 sequenceOfCoinTosses
 [1] 1 1 1 -1 -1 1 -1 1 -1 -1 ...

If we run the same code again, we will get a different sequence of 1’s and -1’s.

If we want to look at our cumulative p&l for this single run, we can use the cumsum() function and then plot() the result.

 plot(cumsum(sequenceOfCoinTosses), type = 'l')

Coin toss experiment in R

Tossing a coin 1000 times



So, after 1000 tosses we can see from the plot that we ended up approximately $6.
Now, let’s repeat this game 10000 times and see what our final p&l ends up being each time. I will store every final p&l value in a list() container and then use the unlist() command to create a vector that I can subsequently plot using the hist() function.

 # Create an empty list to store the results
 results <- list()
 for(i in 1:10000) {
     coinTosses   <- cumsum(sample(c(-1,1), 1000, replace = TRUE)) 
     results[[i]] <- coinTosses[length(coinTosses)]
 }
 
 # Unlist the list and create a histogram. Set a title and set the color and breaks
   hist(unlist(results), main = "Histogram of all the final p&l's",col = "lightblue", breaks = 100)
 
 # Place a vertical line at 0 with a width of 2 in order to show the average of the distribution
 abline(v = 0, col = "red", lwd = 2)

Here’s what this code generates:

Generate a coin toss in R histogram

Histogram of final p&l

No comments yet.

Leave a Reply