### Stat 3601 # generate a uniform(0,1) pseudo-random number help(runif) # get help on random uniform command u <- runif(1) # generate a single random uniform value u # prints u # generate N = 1000 uniform(0,1) pseudo-random number and plot N <- 1000 # number of interation u <- runif(N) # create a vector of N uniforms plot(u) # plots the random uniforms plot(u, type = "l") # plots connecting the lines # flip a fair coin 1 time p <- 0.50 # P(H) = 0.5 H <- 0 # counter for H u <- runif(1) # generate a single random uniform value u if(u < p) H <- 1 # simulate 1 flip of a fair coin H # print the result, 0 is T and 1 is H # flip a fair coin N times N <- 1000 p <- 0.50 H <- 0 for(i in 1:N){ u <- runif(1) if(u < p) H <- H + 1 } H p.hat <- H/N # estimated probability of H p.hat # make a plot that shows the relative frequency interpretation # of probability N <- 1000 # number of flips p <- 0.50 # probability of H u <- runif(N) # create a vector of N uniforms H <- numeric(N) # create a vector of N 0's for(i in 1:N){ # simulate flipping the coin if(u[i] < p) H[i] <- 1 } H.cumsum <- cumsum(H) # sum up the number of H #H.cumsum p.hat <- numeric(N) for(i in 1:N){ p.hat[i] <- H.cumsum[i]/i } p.hat plot(p.hat, type = "l") # roll a fair die 1 time u <- runif(1) u D <- trunc(6*u) + 1 D # roll a fair die N times and estimate P(3) N <- 1000 u <- runif(N) D <- trunc(6*u) + 1 br <- c(0.5,1.5,2.5,3.5,4.5,5.5,6.5) hist(D, breaks = br) Count <- 0 for(i in 1:N){ if(D[i] == 3) Count <- Count + 1 } Count/N # roll a pair of fair dice N times N <- 1000 u1 <- runif(N) D1 <- trunc(6*u1) + 1 u2 <- runif(N) D2 <- trunc(6*u2) + 1 D <- D1 + D2 br <- seq(0,12) + 0.5 hist(D, breaks = br)