Professional Documents
Culture Documents
Monte Carlo Dice Rolling
Monte Carlo Dice Rolling
This program determines the odds of rolling a target number between 2 and 12 inclusive with
two six-sided dice.
Assuming the dice are not “loaded,” the odds are equal that any number between one and six
inclusive will be rolled on a single die. The sum of the numbers rolled from two dice will
therefore be between 2 and 12 inclusive. The odds of rolling any number between 2 and 12
inclusive can simply be calculated by counting the number of times the target number occurs in
the following table (black values) and dividing by the total number of possibilities, that is, 36.
Die roll 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12
For example the odds of rolling a total of 7 with two dice is 6/36 or 1/6 while the odds of rolling
2 is only 1/36.
Instead of generating a random number between zero and one as was done in the example of
sleeping students, we want to simulate the result of each die roll by generating an integer number
between 1 and 6 inclusive with equal probability for each result. There are a number of ways to
do this. One way is with the following two statements
call random_number(r)
dr1 = ceiling(6.*r)
where dr1 is a type integer variable that is set equal to the die roll of one die, that is, an integer
between 1 and 6 inclusive. ceiling is an intrinsic Fortran function that converts the floating-point
value in the parentheses to the nearest integer, rounded up.
For example, set up variables dr1 and dr2 for the results of the rolls of the two dice, a variable
target that is the target number between 2 and 12 that you have selected to calculate the odds of
rolling, and a “counter” kount in which are stored the number of trials in which the total of the
roll of two dice is equal to the target value.
integer :: dr1, dr2, target, kount
To test whether the sum of the two dice equals the target number you have selected, use a
statement of the form
if (dr1 + dr2 == target) then kount = kount + 1
1
EGMN 560 – Monte Carlo Methods – Dice Rolling Example
Important! Notice the use of a double equals sign (==) to test for equality. In many
programming languages the use of a single equals sign (=) means store the result of the
calculation on the right side of the equals sign in the storage location represented by the variable
on the left hand side of the equals sign. For example, the above statement
dr1 = ceiling(6.*r)
takes the result of six times the value of a random number r (between zero and one), rounds it up
to the nearest integer, and stores the result in dr1.
implicit none
2
EGMN 560 – Monte Carlo Methods – Dice Rolling Example