Random Numbers

Random Numbers#

The question mark ? implements the “roll” function in APL.

?n will return a number pseudo-randomly selected from the integers in with each integer having an equal chance of being selected.

List the first 6 integers

6
1 2 3 4 5 6

Now generate one of them at random:

?6
4

Try again, it has a 1 in 6 chance of being the same:

?6
3

If you kept executing ?6, it would be like rolling a 6-sided die over and over. But what if we have 5 dice?

?6 6 6 6 6
4 2 1 4 5

APL functions can take arrays as arguments and return arrays as results.

Here’s another way of rolling 5 dice at once:

?56
3 2 2 2 2

Now let’s look at some ideas about probability.

The casino table game known as “craps” uses 2 6-sided dice that are added to give results in the range of 2-12. The table of all possible rolls looks like this:

6 6
┌───┬───┬───┬───┬───┬───┐ │1 1│1 2│1 3│1 4│1 5│1 6│ ├───┼───┼───┼───┼───┼───┤ │2 1│2 2│2 3│2 4│2 5│2 6│ ├───┼───┼───┼───┼───┼───┤ │3 1│3 2│3 3│3 4│3 5│3 6│ ├───┼───┼───┼───┼───┼───┤ │4 1│4 2│4 3│4 4│4 5│4 6│ ├───┼───┼───┼───┼───┼───┤ │5 1│5 2│5 3│5 4│5 5│5 6│ ├───┼───┼───┼───┼───┼───┤ │6 1│6 2│6 3│6 4│6 5│6 6│ └───┴───┴───┴───┴───┴───┘

And the totals are given by summing “each” roll, in this case using APL’s “each” operator ¨

+6 6
2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9 5 6 7 8 9 10 6 7 8 9 10 11 7 8 9 10 11 12

So first, let’s create a function to compute the elements in the range of results.

range{(¯1+⍴,)↓⍳+/}
range 6 6
2 3 4 5 6 7 8 9 10 11 12
graph{⍉↑t n('⎕'⍨¨0.5+20×{÷⌈/}n+/(t∪,+)∘.=+?⍴⊂)}
10000 graph 6 6
┌──┬────┬────────────────────┐ │2 │271 │⎕⎕⎕ │ ├──┼────┼────────────────────┤ │3 │582 │⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │4 │908 │⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │5 │1099│⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │6 │1387│⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │7 │1676│⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕│ ├──┼────┼────────────────────┤ │8 │1368│⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │9 │1087│⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │10│748 │⎕⎕⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │11│593 │⎕⎕⎕⎕⎕⎕⎕ │ ├──┼────┼────────────────────┤ │12│281 │⎕⎕⎕ │ └──┴────┴────────────────────┘