## Problem 1: ## a = 0.5 b = 1 the.prob = pexp(b)-pexp(a) the.same.prob = 1-exp(-b) - (1-exp(-a)) ## Problem 2a: ## reps = 1e5 y.vec = rexp(reps) ## Problem 2b: ## ## The Slow Way: count = 0 for ( i in 1:reps ) { if( (a <= y.vec[i] ) & (y.vec[i] < b) ) { count = count + 1 } } count ## The Fast Way: count = sum( (a <= y.vec ) & (y.vec < b) ) count ## Problem 2c: ## sim.prob = count / reps sim.prob ## The Entire Simulation: y.vec = rexp(1e5) sim.prob = mean( (0.5 <= y.vec ) & (y.vec < 1) ) ## Problem 3: ## ## Start Vectors to store exact/simulated probs exact.vec = NULL sim.vec = NULL ## Generate 1e5 realizations from a standard Exponential distribution y.vec = rexp(1e5) ## Create a vector of the left-cut points for the probs a.vec = seq(0, 1.5, by=0.5) for ( k in 1:length(a.vec) ) { a = a.vec[k] b = a + 0.5 exact.vec[k] = pexp(b)-pexp(a) sim.vec[k] = mean( (a <= y.vec ) & (y.vec < b) ) ## Print the result cat("P(", a, "<= Y <", b,")\t", exact.vec[k], "\t", sim.vec[k], "\n", sep="") } ## Problem 4: ## ## Start Vectors to store exact/simulated probs exact.vec = NULL sim.vec = NULL ## Generate 1e5 realizations from a standard Uniform distribution u.vec = runif(1e5) ## Make y.vec from the u.vec y.vec = log(1/u.vec) ## Create a vector of the left-cut points for the probs a.vec = seq(0, 1.5, by=0.5) for ( k in 1:length(a.vec) ) { a = a.vec[k] b = a + 0.5 exact.vec[k] = pexp(b)-pexp(a) sim.vec[k] = mean( (a <= y.vec ) & (y.vec < b) ) ## Print the result cat("P(", a, "<= Y <", b,")\t", exact.vec[k], "\t", sim.vec[k], "\n", sep="") } ## Coin Flipping ## ## The number of simulated games. reps = 1e4 winnings.vector = NULL ## Games loop. for (r in 1:reps) { ## To start a sequence of bets, set his winnings ## to zero winnings = 0 last.flip = 0 ## Start flipping until we win 2 times in a row while (1) { ## Flip the fair coin this.flip = 1*(runif(1) > 0.5) ## 1=Heads, 0=Tails ## Add 1 dollar to our winnings if we got heads, ## and subtract 1 if we got tails winnings = winnings + 1 - 2*(this.flip == 0) ## Stop flipping when we have 2 consecutive heads if ((this.flip==1) & (last.flip == 1)) { break } last.flip = this.flip } winnings.vector[r] = winnings } mean(winnings.vector)