--- title: "Homework 5 Help: Simulating Expectation and Variance" author: "Tom Fletcher" date: "October 19, 2017" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, comment = "") ``` Thus far, we have been simulating random variables in R and checking that the frequency of simulated events approximately match the probabilities that we get with paper and pencil. We can also check properties of a simulated random variable, such as the expected value and variance. ## Die Roll First, let's simulate the six-sided die roll experiment. ```{r} N = 10000 dieSims = sample(1:6, N, replace = TRUE) ``` We know from class that the expectation is $E[X] = 3.5$ and the variance is $\mathrm{Var}(X) = 35/12 \approx 2.92$. Estimating these values from the simulation is just a single function call in R. The simulated expected value is: ```{r} mean(dieSims) ``` And the simulated variance is: ```{r} var(dieSims) ``` ## Evil Problem Here is the simulation of the expected value of the number of rolls to get a six, conditioned on only seeing even numbers. As we discussed in class, the correct answer is 1.5. First, we have to set up a function to simulate a single trial. It rejects the sequence if an odd number appears, and starts over from the beginning. This function returns an integer, which is how many rolls it took to get a six. ```{r} evilSim = function() { k = 0 ## counter for number of rolls done = FALSE while(!done) { i = sample(1:6, size = 1) k = k + 1 if(i == 6) ## quit if we get a six done = TRUE else if(i == 1 | i == 3 | i == 5) ## reject and start over if odd k = 0 } return(k) } ``` Now we run the simulation: ```{r} N = 10000 sims = numeric(N) for(i in 1:N) sims[i] = evilSim() ``` And the simulated expected value is: ```{r} mean(sims) ``` Just for fun, the variance is: ```{r} var(sims) ``` See if you can compute the variance on pencil and paper!