Possible outcomes of throwing a single die:We define a uniform probability distribution for the results 1 to 6, and call it "dice":- dice = DiscreteUniformDistribution[{1, 6}];
复制代码 How many times we toss the die => trials:Toss it:- toss = Table[RandomVariate[dice], trials]
复制代码 {3,3,6,5,2,3,2,5,3,2,1,2,3,6,4,5,1,4,6,4,3,5,4,6,1,2,4,2,4,2,1,2,3,6,5,2,1,1,1,3,4,2,1,4,2,5,1,5,1,4,2,4,2,5,1,2,6,6,2,6,5,4,5,2,6,2,4,3,2,1,4,4,5,5,2,3,3,5,6,2,3,5,6,4,5,4,2,3,2,4,5,1,2,4,2,3,2,1,4,4,2,3,1,1,5,6,1,1,2,4,5,2,1,4,2,2,1,6,2,5}
Count how many of each number (between 1/2 and 3/2, 3/2 and 5/2, etc):
- freq = BinCounts[toss, {.5, 6.5, 1}]
复制代码 {20, 31, 15, 22, 19, 13}
Plot the frequency of each result as a histogram:
Efficient way to add up the elements of the list "dots" ==> Apply the "Plus" operator to each element:21
Calculate the average value of the number of dots:
- N[Plus @@ (freq*dots) / trials]
复制代码
3.23333
Calculate the average value of the number of dots squared:
- N[Plus @@ (freq*dots^2) / trials]
复制代码
13.1167
- Rolldice[trials_] := (
- dots = Range[6];
- dice = DiscreteUniformDistribution[{1, 6}];
- toss = Table[RandomVariate[dice], trials];
- freq = BinCounts[toss, {.5, 6.5, 1}];
- BarChart[freq];
- avgdots = N[Plus @@ (freq*dots)/trials];
- avgdotssq = N[Plus @@ (freq*dots^2)/trials];
- sdev = Sqrt[avgdotssq - avgdots^2];
- Print["mean = ", avgdots, " standard deviation = ", sdev])
复制代码
Let's define a function to evaluate mean and standard deviation: |
| Compare with the formulas for discrete uniform distribution: | \begin{aligned}\frac{6+1}2&=3.5\\\sqrt{\frac{6^2-1}{12}}&=1.70783\end{aligned} |
|