Example with Simulated Data Sets

Coin Flipping

Imagine flipping a coin 100 times.  What is the probability that you will get 60 or more heads?

Simulation

There are analytical ways to answer this question, but let's just simulate a large number of experiments, and see what we get.

?RandomReal

?RandomInteger

RandomInteger[]

The following cell will "flip a coin" 100 times (or,  more generally, nFlip times) and count up the number of heads.

nFlips = 100;
heads = 0;
For[i=1,i≤ nFlips,++i,heads+= RandomInteger[]]
heads

More compact version of "flipping a coin" 100 times

nFlips  = 100;
Total[RandomInteger[{0,1},nFlips]]

Now lets do this "experiment" 200 times, using a For loop:

nFlips = 100;   (* Number of flips *)
nEx = 200;   (* Number of "experiments" *)
simData = Table[0,{i,1,nEx}];  (* List for results of each expt *)
For[j=1,j<=Length[simData],++j,
{heads = 0;
For[i=1,i≤ nFlips,++i,heads+= RandomInteger[]],
simData[[j]] = heads;}]

simData

More compact version of repeating experiment 200 times

nFlips  = 100;
nEx = 200;
simData = Table[Total[RandomInteger[{0,1},nFlips]],{i,1,nEx}];

simData

Mean[simData]//N
StandardDeviation[simData]//N

?Histogram

Histogram[simData]

Count number of "experiments" that result in 60 or more heads :

limit = 60;
num = 0;
For[i=1,i<=Length[simData],++i,If[simData[[i]]≥ limit,++num]]
num

probability = num/nEx

probability = num/nEx//N

Alternative way to count the number of experiments that result in 60 or more heads :

BinCounts[simData,{{0,60,nEx}}]

BinCounts[simData,{{0,60,nEx}}]/nEx//N

Alternative solution using properties of binomial distribution

There are other ways to calculate the probability of 60 or more heads, and Mathematica can be useful in these methods too.   Taking a peek ahead ...
 
The distribution of the number of heads in "n" tosses is an example of a Binomial Distribution, which we will study in more detail later.

?BinomialDistribution

nFlips  = 100; (* Number of coin flips *)

The mean number of heads is exactly what we expect :

Mean[BinomialDistribution[nFlips,1/2]]

The standard deviation is consistent with the histograms above :

StandardDeviation[BinomialDistribution[nFlips,1/2]]

The Cumulative Distribution Function (CDF) gives the total probability for getting a number of heads between 0 and some number (here 59).

1-CDF[BinomialDistribution[nFlips,1/2],59]//N