# Modeling Die Rolls

Modeling out die rolls seems pretty straight forward.  Let’s say that you wanted to figure out the distribution of sums. The brute force method for doing this looks like the following chunk of perl code:

```sub dist {
my (\$count, \$sides) = @_;
my \$state = [];
for (my \$i = 0; \$i < \$count; \$i++) {
\$state->[\$i] = 1;
}

my \$max = \$count * \$sides;
my \$result = [];
while(1) {
my \$sum = 0;
for (my \$i = 0; \$i < \$count; \$i++) {
\$sum += \$state->[\$i];
}

\$result->[\$sum]++;
last if \$sum >= \$max;
\$state->++;
for (my \$i = 0; \$i < \$count; \$i++) {
last if \$state->[\$i] [\$i] = 1;
\$state->[\$i+1]++;
}
}
return \$result;
}```

This seems to work well for distributions of same sided dice. What if I wanted to combine multiple types of dice? Say, 4x six sided dice and 8 4-sided dice… well, the brute force method starts to get pretty expensive.

I was reading this lecture on normal distributions for sums and came to the solution to my problem.  Instead of iterating over all sums for all dice, I could probably just add the normal curves for the die rolls.

How do you compute a normal distribution? It’s called a Gausian… check the Wikipedia page!  The code for a gausian given two params, mu and sigma look like so:

```sub gausian {
my (\$x, \$mu, \$sigma) = @_;

my \$exp = - 1/2 * ((\$x - \$mu) / \$sigma) ** 2;
return 1/(\$sigma * sqrt(2 * \$pi)) * exp(\$exp);
}```

Now I just need to figure out how to scale mu and sigma (mean, std deviation) to number of dice and the sides per die.  The lecture above seems to model 6 sided dice well with a mean of 3.5 x number of dice and 1.7 * sqrt(num of dice) but I need to expand that out to other side counts for this to work.

## 2 thoughts on “Modeling Die Rolls”

1. Andrew

The easiest way to compute mu and sigma is to actually compute it. mu = sum( X * P(X) ) for all values of X.
sigma^2 = P(x) * (X – mu)^2 for all values of X.

so, for a 4-sided die, P(X) = .25 for all values of X.
mu = .25 * 1 + .25 * 2 + .25 * 3 + .25 * 4 = .25 (1 + 2 + 3 + 4) = 2.5
sigma^2 = .25 * (1 – 2.5)^2 + .25 * (2 – 2.5)^2 + .25 * (3 – 2.5)^2 + .25 * (4 – 2.5)^2
= .5 * 1.5^2 + .5 * .5^2 = .5 * (2.25 + .25) = .5 * 2.5 = 1.25

So, sigma = sqrt(1.25).

The only problem is that it is all an approximation. There may be more effective ways to do what you’re looking for. I’d try to help, but I can’t read perl. 1. Richard Post author

That makes sense.

As I get further into this i may ping you!