Lab 7
Remember, follow the instructions below and use R Markdown to create a pdf document with your code and answers to the following questions on Gradescope. You may find a template file by clicking “Code” in the top right corner of this page.
A. Random sampling in R
In your own words, explain the difference between
dnorm(),pnorm(),qnorm(), andrnorm().Suppose we simulate
x <- runif(1). What is the distribution ofqnorm(x)?Suppose we simulate
x <- rnorm(1). What is the distribution ofpnorm(x)?
B. Gambler’s ruin
A and B are playing a coin flipping game. A starts with \(n_a\) pennies and B starts with \(n_b\) pennies. A coin is flipped repeatedly and if it comes up heads, B gives A a penny. If it comes up tails, A gives B a penny. The game ends when one player has no more pennies.
Write a function
run_one_sim(seed, n_a, n_b)to simulate one game. Repeatedly use your code with different values ofseedto estimate each player’s probability of winning when \(n_a = n_b = 10\).Use your function to estimate each player’s probability of winning when \(n_a = 1,\ldots, 5\) and \(n_b = 1,\ldots, 5\), testing every combination. Organize your results in a 5 by 5 matrix and print it out. What do you notice?
C. One-dimensional random walks
In this part, you will simulate a one-dimensional random walk. Suppose you are at the point \(x\) at time \(t\). At time \(t+1\), the probability of moving forwards to \(x+1\) is \(p\) and the chance of moving backwards to \(x-1\) is \(1-p\). Assume that at time \(t=1\), you are at \(x_1=0\).
Write a function
random_walk()that takes as input a numericn_stepsand a numeric \(p\) and simulatesn_stepssteps of the one-dimensional random walk with forward probability \(p\). You may have other input arguments if desired. The output should be a length vector of lengthn_stepsstarting with 0 where the \(i\)th entry represents the location of the random walker at time \(t=i\). For example,random_walk(5, .5)may return the vector \((0, 1, 2, 1, 2)\).Use your function to generate a random walk of 500 steps with probability \(.55\) and generate a line graph with \(t=1,\ldots, 500\) on the x-axis and \(x_1,\ldots, x_{500}\) on the y-axis.
Use your function to generate two more random walks of 500 steps with probability \(p\), where \(p\sim \mathrm{Unif}(0, 1)\) and create a line graph with all three of your random walks, using different colors for each walk.