Chapter 1

Load Graphics Packages

<<Graphics`Graphics`
Off[General::spell1];
NotebookOpen["classes:chapter1:palette.nb"];

CoinTosses

Examples

?CoinTosses

CoinTosses[50]

CoinTosses[100, Print->False]

CoinTosses[100, Print->False, p->.8]

The code

(* Define what CoinTosses does -- activivate with ?CoinTosses *)
CoinTosses::usage ="CoinTosses[n] returns the result of tossing a fair  coin n times
and graphing the relative frequency of heads and tails. Add the
Print->False option to supress the printing of the acutual flips.
Also  use the p->.ddd option to change the probability of heads
from .5 to  .ddd.";

(* set the default options *)
Options[CoinTosses] =  {p->.5,  Print->True};

(* create CointTosses *)
CoinTosses[(n_Integer)?Positive, opts___] :=  
  Module[
       (* reserve variables *)
       {heads, outputstring, relfreq, print,prob}, 
       
       (* set up the options *)
        {print,prob} = {Print,p} /. {opts} /. Options[CoinTosses];
        
       (* do the experiment *)
        flip := If[Random[]<prob,1,0]; 
        heads = Table[flip, {n}]; 
        relfreq= N[Apply[Plus,  heads]/n];
        
       (* do the output with graphics *)   
        If[print ==  False, outputstring = "", 
        outputstring = StringJoin[heads /. {1 -> "H", 0 -> "T"}]]; 
        
        BarChart[{{relfreq,"Heads"},{1-relfreq,"Tails"}},
        Gridelines ->Automatic, BarSpacing ->-.2,PlotRange->{0,1},
         PlotLabel->FontForm["Coin Tosses",{"Helvetica-Bold",12}],
        BarStyle->{RGBColor[1,0,0],RGBColor[0,0,1]},
        DefaultFont->{"Helvetica",10}]; 
        
        Print[StringForm["``\n\nThe proportion of heads in `` tosses is ``.",  
              outputstring, n, relfreq, 5]];
        ]

DeMere

DeMere1

Examples

?DeMere1

DeMere1[100]

DeMere1[100, Rolls->9]

DeMere1[1000,Print->False]

The Code

(* Define what DeMere1 does -- activivate with ?DeMere1  *)
DeMere1::usage ="DeMere1[n] returns the result of 4 rolls of 1 die
and repeating the experiment n times. A success occurs if at least
one six occurs in the 4 rolls. The results returned is the 
graph of the relative frequency of number of successes.
Add the Print->False option to supress the printing  of the success and failures.
Add the Dice->k options to change the number  of dice rolled from 
4 to k. ";

(* set the default options *)
Options[DeMere1] =  {Print->True, Rolls->4};

(* create DeMere1 *)
DeMere1[(n_Integer)?Positive, opts___] := 
  Module[
       (* reserve variables *)
       {successes, outputstring, relfreq, print,size},  
       
       (* set up the options *)
        {print,rolls} = {Print,Rolls}  /. {opts} /. Options[DeMere1];
       
       (* do the experiment  *)
        toss := If[Random[]<1/6,1,0]; 
        sixes = Table[If[Apply[Plus,Table[toss,{rolls}]]>0,1,0], {n}]; 
        relfreq= N[Apply[Plus, sixes]/n,5];
        
       (* do the output with  graphics *)   
        If[print == False, outputstring = "", 
         outputstring = StringJoin[sixes /. {1 -> "S", 0 -> "F"}]]; 
        
        BarChart[{{relfreq,"Success"},{1-relfreq,"Failure"}},
         Gridelines ->Automatic, BarSpacing ->-.2,PlotRange->{0,1},
        BarStyle->{RGBColor[1,0,0],RGBColor[0,0,1]},
        PlotLabel->FontForm["De Mere 1",{"Helvetica-Bold",12}],
        DefaultFont->{"Helvetica",10}]; 
        
        Print[StringForm["``\n\nThe proportion of successes (at least one  six)
in `` repetitions of `` rolls of a die is ``.", outputstring,n, rolls,relfreq]];
        ]

DeMere2

Examples

?DeMere2

DeMere2[100]

DeMere2[100,Print->False]

DeMere2[100,Rolls->30]

DeMere2[100, Dice->3,Rolls->40,Print->False]

The Code

(* Define what DeMere2 does -- activivate with ?DeMere2  *)
DeMere2::usage ="DeMere2[n] returns the result of 24 rolls of 2 die
and repeating the experiment n times. A success occurs if at least
one double six occurs  in the 24 rolls. For k dice, a success
occurs if at least one set of all k  dice are 6 in m rolls.
The results returned is the graph of the relative frequency of the number of successes.
Add the Print->False option to  supress the printing of the success and failures.
Add the Dice->k options to  change the number of dice rolled from 
2 to k. Add the Rolls->m option to  change the number times the set
of dice is rolled from 24 to m";


(* set  the default options *)
Options[DeMere2] =  {Print->True, Rolls->24,  Dice->2};

(* create DeMere2 *)
DeMere2[(n_Integer)?Positive, opts___] := 
   Module[
       (* reserve variables *)
       {successes, outputstring, relfreq, print,size}, 
       
       (* set up the options *)
        {print,rolls,dice} = {Print,Rolls,Dice} /. {opts} /.  Options[DeMere2];
       
       (* do the experiment *)
        toss := If[Sum[If[Random[]<1/6,1,0],{dice}]==dice,1,0]; 
        sixes = Table[If[Apply[Plus,Table[toss,{rolls}]]>0,1,0], {n}]; 
        relfreq= N[Apply[Plus, sixes]/n,5];
        
       (* do the output with  graphics *)   
        If[print == False, outputstring = "", 
         outputstring = StringJoin[sixes /. {1 -> "S", 0 -> "F"}]]; 
        
        BarChart[{{relfreq,"Success"},{1-relfreq,"Failure"}},
         Gridelines ->Automatic, BarSpacing ->-.2,PlotRange->{0,1},
        BarStyle->{RGBColor[1,0,0],RGBColor[0,0,1]},
        PlotLabel->FontForm["De Mere 2",{"Helvetica-Bold",12}],
        DefaultFont->{"Helvetica",10}]; 
        
        Print[StringForm["``\n\nThe proportion of successes (at least one set  of 
all sixes)
in `` repetitions of `` rolls of a set of `` dice is ``.", outputstring,n, rolls,dice,relfreq]];
        ]

GeneralSimulation

Examples

?GeneralSimulation

GeneralSimulation[100,{.1,.4,.2,.1,.2}]

GeneralSimulation[1000,{.1,.1,.2,.1,.1,.1,.3}]

The Code

\(\(
GeneralSimulation::usage\  = " GeneralSimulation[n,plist]
This program simulates a general experiment in which the outcomes 1, 2, 
..., k

 occur with probabilties p(1), p(2), ..., p(k). (k=Length[plist]). These 
probabilities are entered as a
 list in plist.  The experiment is repeated n times, and the observed 
frequencies of
 the outcomes are graphed and printed.  The observed data spikes are 
topped 
with 
 blue dots, and the plist data spikes are topped with red.  Finally, the 
program
 returns a list of the observed frequencies."; 
\ \ \ \ \ \ \ \ 

    \ \ \ \ \ \ \ \ Clear[GeneralSimulation]; 

    GeneralSimulation[n_, \ plist_]\  := 


      Module[{frequencies, pick, clist = FoldList[Plus, 0, plist] // Rest, 

          \ \ \ \ \ \ \ 
\ \ \ \ \ \ \ linelist, \ pointlist, plinelist, 
          ppointlist}, 
\ \ \ \ \ \ 
\ \ \ \ \ \ 
        pick[x_] := 
          Block[{r, \ j\  = \ 1}, 
\ \ \ \ \ \ r\  = \ Random[]; 

            \ \ \ \ \ \ While[x[\([j]\)]\  <= \ r, \(j++\)]; Return[j]]; 

        \ \ \ \ \ \ 
\ \ \ \ \ \ observedlist = Table[pick[clist], {n}]; 

        \ \ \ \ \ \ 
        observedrelfreq = 
\ \ \ \ \ \ 
          Map[\(({#, N[Count[observedlist, #]/n, 3]})\)&, 
            Union[observedlist]]; 
\ \ \ \ \ \ 
        dist = Transpose[{Range[Length[plist]], plist}]; 
\ \ \ \ \ \ 

        \ \ \ \ \ 
        linelist = 
          Table[Line[{{i, 0}, dist[\([i]\)]}], {i, Length[observedrelfreq]}]; 
        
\ \ \ \ \ \ pointlist = Map[Point, observedrelfreq]; 
\ \ \ \ \ \ 
        ppointlist = Map[Point, dist]; 
\ \ \ \ \ \ 
\ \ \ \ \ \ 

        \ \ \ \ \ \ 
        Show[Graphics[linelist], 
\ \ \ \ \ \ \ \ \ \ \ \ \ \ 
          Graphics[{

              \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ {PointSize[.03], 
                RGBColor[1, 0, 0], ppointlist}, 

              \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ {PointSize[.02], \ 
                RGBColor[0, 0, 1], pointlist}}

            \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ], 

          \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 
\ \ \ \ \ \ \ \ \ \ \ \ \ \ 
          PlotRange\  -> \ All, \ 
          PlotLabel -> "Blue=observed, Red=expected", 

          \ \ \ \ \ \ \ \ \ \ \ \ \ \ Frame\  -> \ True, 
          FrameTicks -> {Range[Length[plist]], Automatic}

          \ \ \ \ \ \ \ \ \ \ \ \ \ ]; 
\ \ \ \ \ \ 
        observedrelfreq // TableForm\ 
\ \ \ \ \ \ ]\)\)

HorseRace

Examples

?HorseRace

HorseRace[100]

HorseRace[10,Print->True]

HorseRace[1000,Plist->{.1,.2,.3,.4}]

The Code

HorseRace::usage="HorseRace[n,opts]. This program simulates n of the horse races described in 
Chapter 1.  The program graphs the actual and  the expected percentage of the time each
horse wins. The default probability  is Plist->{.3,.4,.2,.1} for {Acorn, Balky,Chestnut, Dolby}.  This option
  can be changed by adding Plist->{p1,p2,p3,p4} where p1+p2+p3+p4=1.
 The  default option is to not print the horses as they win each race. This may be  changed with
the option Print->True.";


 Clear[HorseRace];
Options[HorseRace]={Plist->{.3,.4,.2,.1},Print->False}; 
 
HorseRace[n_,opts___]  :=

Module[{frequencies,pick,clist,plist,print,
       linelist, pointlist,plinelist,ppointlist},
     {print,plist} = {Print,Plist} /. {opts} /. Options[HorseRace];
     clist=FoldList[Plus,0,plist]//Rest;
      pick[x_]:=Block[{r, j =  1},
      r = Random[];
      While[x[[j]] <= r,j++];Return[j]];
      
      observedlist=Table[pick[clist],{n}];
      observedrelfreq=
      Map[({#,N[Count[observedlist,#]/n,3]})&,Union[observedlist]];
     
     
      If[print==True, Print[observedlist /. {1->"Acorn", 2->"Balky",3->"Chestnut",4->"Dolby"}]];
      
      DisplayTogetherArray[
      PieChart[Transpose[observedrelfreq][[2]],PieLabels->{"Acorn","Balky","Chestnut","Dolby"},
      PlotLabel->"ACTUAL"],
       PieChart[plist,PieLabels->{"Acorn","Balky","Chestnut","Dolby"},
      PlotLabel->"EXPECTED"]
      ];
      
          
      observedrelfreq /. {1->"Acorn",  2->"Balky",3->"Chestnut",4->"Dolby"} //TableForm 
      ]

HTSimulation

Examples

?HTSimulation

HTSimulation[1000,10]

HTSimulation[1,100]

HTSimulation[16,10,Print->True]

The Code

HTSimulation::usage="HTSimulation[n_, m_] 
 This program simulates an experiment in which a fair coin is tossed  m times. 
The experiment is repeated n times.  The program records the `winnings` in each
 experiment, where the winnings are defined to be the number of heads minus
the number of tails.  It also keeps track of the number of times the winnings are
`positive` in the course of an  experiment (we count as `positive` a time at which
 the winnings are 0 but the  previous winnings are positive).   The program returns
a list  of the winnings in each experiment and the 'leadings' which are the number of times
heads  is leading over tails in the m tosses. The default option is not to print  the values. This
is changed by the option Print->True. ";
     
  Clear[HTSimulation];
 Option[HTSimulation]={Print->False} ;      

HTSimulation[1,m_]:=ListPlot[trial=
FoldList[Plus,0,Table[(-1)^Random[Integer],{m}]],PlotJoined->True];

HTSimulation[n_, m_, opts___] :=
   Module[{lead,trial,outcomes},
 
  {print} = {Print} /. {opts} /. Options[HTSimulation];
     
outcomes=Table[
    trial=FoldList[Plus,0,Table[(-1)^Random[Integer],{m}]];
     lead=trial //. {{x___,_?Negative,y___}->{x,y},{x___,0,0,y___}->{x,0,y}};
    {Last[trial],Length[lead]-1},{n}];
     outcomes = Transpose[outcomes];

observedwin=
  Map[({N[Count[outcomes[[1]],#],3],#})&,Union[outcomes[[1]]]];
observedlead=
  Map[({N[Count[outcomes[[2]],#],3],#})&,Union[outcomes[[2]]]];

DisplayTogetherArray[
BarChart[observedwin,
        Gridelines ->Automatic, BarSpacing ->-.2,PlotRange->All,
        PlotLabel->FontForm["Winnings",{"Helvetica-Bold",12}],
        DefaultFont->{"Helvetica",10}],

BarChart[observedlead,
        Gridelines ->Automatic, BarSpacing ->-.2,PlotRange->All,
        PlotLabel->FontForm["Leadings",{"Helvetica-Bold",12}],
        DefaultFont->{"Helvetica",10}]];

If[print, Print["Winnings= ",outcomes[[1]]]];
If[print, Print["Leadings=  ",outcomes[[2]]]];

             
     ]

RandomNumbers

Examples

?RandomNumbers

RandomNumbers[10]

RandomNumbers[10,Print->True]

RandomNumbers[100]

The Code

RandomNumbers::usage="Random[n] This program generates and displays n
random real numbers between 0  and 1. The default option is not to print  the
numbers. To print the numbers set the option  Print->True  ";

Options[RandomNumbers] = {Print->False};

Clear[RandomNumbers];
RandomNumbers[n_,opts___]:=Module[{linelist},
     
      {print}={Print} /. {opts} /. Options[RandomNumbers];
     
     linelist=Table[Line[{{i,0},{i,Random[]}}],{i,n}];
      Show[Graphics[linelist],PlotRange->{0,1},Frame->True,
      FrameTicks->None];
              
     If[print, linelist[[#,1,2]]& /@ Range[n]// TableForm,{};]
      ]

Palette

({{Chapter 1}, {CoinTosses[\[SelectionPlaceholder]]}, {DeMere1[\[SelectionPlaceholder]]}, {DeMere2[\[SelectionPlaceholder]]}, {GeneralSimulation[\[SelectionPlaceholder], 
              \[SelectionPlaceholder]]}, {HorseRace[\[SelectionPlaceholder]]}, {HTSimulation[\[SelectionPlaceholder], \[SelectionPlaceholder]]
              }, {RandomNumbers[\[SelectionPlaceholder]]}})