# # Written by: # -- # John L. Weatherwax 2009-04-21 # # email: wax@alum.mit.edu # # Please send comments and especially bug reports to the # above email address. # #----- # Exercise 29: # waiting_game = function( nDraws=100, targetNumFlips=3 ){ nFlipsNeeded = matrix( 0., nrow=nDraws ) for( ii in 1:nDraws ){ # Flip a coin until we get a total of targetNumFlips ones: # totalFlips = 0 nOnes = 0 while( nOnes < targetNumFlips ){ flip = rbinom( 1, size=1, prob=0.5 ) totalFlips = totalFlips + 1 if( flip==1 ){ nOnes = nOnes +1 } } nFlipsNeeded[ii] = totalFlips } nFlipsNeeded } # Determining the max/min size of the bins seems to be rather tricky. # Thus we will just hard code the bin size # min_value = 3 max_value = 25 bins = seq( from=(min_value - 0.5), to=(max_value + 0.5), by=1.0 ) nDraws = c(5000,1000,500,100) M = matrix( 0, nrow=length(bins)-1, ncol=length(nDraws) ) for( ii in 1:length(nDraws) ){ wg = waiting_game(nDraws[ii]) M[,ii] = hist( wg, breaks=bins, plot=F )$intensities } #postscript("../../WriteUp/Graphics/Chapter2/prob_29_hist.eps", onefile=FALSE, horizontal=FALSE) barplot( t(M), beside=T, main="MC distribution", ylab="frequency", xlab="5000,1000,500,100 number of experiments" ) #dev.off() # whats the expected number of rolls needed to get three looks like it is ~ 4 # t(M) %*% matrix( 1:(length(bins)-1), nrow=(length(bins)-1), ncol=1 )