%% Discrete probablility simulations, Grinstead and Snell section 1.1 % *Nancy K. Stanton* % % code based in part on Peter Doyle's code %% Random numbers in MATLAB % MATLAB has the command *rand* to generate random numbers between 0 and 1. rand %% % *rand(1,n)* will produce an $n$ component vector of random numbers, so to % get 5 random numbers, I could give the command rand(1,5) %% % To get a table of 20 random numbers like the one on p. 3 which has 5 rows % of 4 numbers, I can give the command rand(5,4) %% Simulating cointossing % I can simulate tossing a fair coin by generating a random number and % calling it heads if it is less than 1/2 and tails if it is greater. % The MATLAB function *cointosses.m* simulates this. To see how it works, I % can give the command *doc cointosses* which will pop up the help for % the command in a separate window. doc cointosses %% % So, if I want to toss a fair coin 20 times, I give the command cointosses(20,1/2) %% % To see the code, I can give the command type cointosses %% % Let's see what happens if we toss the coin 1000 times and repeat this a % 5 times. We probably don't want to list all 1000 outcomes, just the % proportion, which we can do with *cointosses2* which is the same as % *cointosses* except that it only displays the proportion of heads. cointosses2(1000,1/2) %% cointosses2(1000,1/2) %% cointosses2(1000,1/2) %% cointosses2(1000,1/2) %% cointosses2(1000,1/2) %% de Mere's first experiment % Is it reasonable to think that in 4 rolls of a die a 6 will turn up? % The command *demere1(n)* simulates this experiment n times. demere1(100) %% demere1(1000) %% demere1(1000) %% demere1(1000) %% demere1(1000) %% de Mere's second experiment % We'll try this 5 times with 10000 trials, 24 rolls per trial. demere2(10000,24) %% demere2(10000,24) %% demere2(10000,24) %% demere2(10000,24) %% demere2(10000,24) %% % Now we'll do it with 25 rolls, which is the default for *demere2*. demere2(10000) %% demere2(10000) %% demere2(10000) %% demere2(10000) %% demere2(10000) %% % The commands *cointosses*, *cointosses2*, *demere1* and *demere2* are not % built-in MATLAB commands, so if you want to use them, you'll have to % download the m-files and put them in your MATLAB path.