### Simulate flipping a fair coin. ### We will use the Uniform Distribution # simulate one flip of a fair coin p <- 0.5 # assume a fair coin u <- runif(1) # gerneate 1 uniform random number u # print the value h <- 0 # assume h is zero, i.e., flip is a T if(u < p) h <- 1 # if u is < p consider the value a H # if u is > p consider the value a T h # print the simulated value # simulate m flips of a fair coin m <- 1000 # total number of times the coin is flipped, # i.e., the total number of times the experiment is performed h <- numeric(m) # initialize a vector for H h # prints the vector of zeros for(i in 1:m){ # a loop that simulates m flips u <- runif(1) if(u < p) h[i] <- 1 } h # print out the results h[1:10] # print out the first 10 values of h sum(h) # the total number of h's in the m flips p.hat.h <- sum(h)/m # the estimated probability of h's p.hat.h i <- seq(1,m) # generate a sequence from 1 to m h.c <- cumsum(h) # computes the cummulate sum of values h.hat <- h.c/i # relative frequency by the index h.hat plot(h.hat)