Using R: Question 9: probability of throwing two sixes with two dice In this que
ID: 3684857 • Letter: U
Question
Using R:
Question 9: probability of throwing two sixes with two dice
In this question, you will practice calling one function from within another function. We will
estimate the probability of rolling two sixes by simulating dice throws. (The correct probability
to four decimal places is 0.0278, or 1 in 36).
Create a function roll.dice() that takes a number ndice and returns the result of rolling
ndice number of dice. These are six-sided dice that can return numbers between 1 and 6.
For example roll.dice(ndice=2) might return 4 6. Use the sample() function, paying
attention to the replace option.
Now create a function prob.sixes() with parameter nsamples, that first sets j equal to 0,
and then calls roll.dice() multiple times (nsample number of times). Every time that
roll.dice() returns two sixes, add one to j. Then return the probability of throwing two
sixes, which is j divided by nsamples.
Explanation / Answer
Code is demonstrated below:
public static IEnumerable<KeyValuePair<int, int>> prob.sixes(int nDice, int nSides)
{
int maximumOutcome = (nDice * nSides);
Dictionary<int, int> outcomeCounts = new Dictionary<int, int>();
for(int j = 0; j <= maximumOutcome; j++)
outcomeCounts[j] = 0;
foreach(int possibleOutcome in roll.dice(0, nDice, nSides))
outcomeCounts[possibleOutcome] = outcomeCounts[possibleOutcome] + 1;
return outcomeCounts.Where(kvp => kvp.Value > 0);
}
private static IEnumerable<int> roll.dice(int currentTotal, int nDice, int nSides)
{
if (nDice == 0) yield return currentTotal;
else
{
for (int i = 1; i <= nSides; i++)
foreach(int outcome in roll.dice(currentTotal + i, nDice - 1, nSides))
yield return outcome;
}
}
There are actually 36 outcomes for two dice ie. 1/6 x 1/6 = 1/36
In a single step : sum(sample(1:6, size = 2, replace = TRUE))
dice.sum <- function(n.dice){
dice <- sample(1:6, size = n.dice, replace = TRUE)
return(sum(dice))
}
Can use replicate function, that compute the sum for rolling dices:
In Mathematics terms :
The probability generating function for one die is
p(y) = y+ y2 + y3 + y4+ y5+ y6 = y(1y6 / 1y).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.