Modula-2 random numbers
last modified November 27, 2026 Modula-2
Neither PIM nor the ISO standard has a module for random numbers. GNU
Modula-2 ships one of its own, RandomNumber, together with
its ISO library. It returns random integers in a range and random reals
between 0 and 1, and it can be seeded for repeatable runs. The module is
specific to gm2; another compiler needs a different module or a generator
of its own, like the one in the
local modules article.
RandomNumber uses the rand function of the C
library. That is good enough for games, tests and simple simulations, but
not for cryptography. All examples are compiled with -fiso.
Random reals
RandomReal returns a REAL from 0.0 to 1.0. The
module seeds itself from the clock when the program starts, so nothing
else is needed.
MODULE reals;
FROM STextIO IMPORT WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM RandomNumber IMPORT RandomReal;
VAR
i: CARDINAL;
BEGIN
FOR i := 1 TO 5 DO
WriteFixed(RandomReal(), 6, 10)
END;
WriteLn
END reals.
Each run prints five different numbers. The module body calls
Randomize, which takes the seed from the microseconds of the
current time, before the program body runs. The two runs below therefore
differ. Both ends of the range are possible, because the procedure divides
a random 64-bit number by the largest one.
$ gm2 -fiso reals.mod -o reals $ ./reals 0.986857 0.839118 0.028128 0.584777 0.956386 $ ./reals 0.121328 0.576751 0.248919 0.731697 0.773026
Random integers
RandomInt(low, high) returns an INTEGER and
RandomCard(low, high) a CARDINAL from
low to high, both bounds included.
MODULE dice;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM RandomNumber IMPORT RandomInt, RandomCard;
VAR
i: CARDINAL;
BEGIN
WriteString("dice: ");
FOR i := 1 TO 10 DO
WriteInt(RandomInt(1, 6), 3)
END;
WriteLn;
WriteString("-5..5: ");
FOR i := 1 TO 10 DO
WriteInt(RandomInt(-5, 5), 3)
END;
WriteLn;
WriteString("0..999: ");
FOR i := 1 TO 5 DO
WriteCard(RandomCard(0, 999), 4)
END;
WriteLn
END dice.
The first line rolls a die ten times. Negative bounds need
RandomInt, and RandomCard fits counts and array
indexes. There are also RandomLongInt,
RandomLongCard and RandomLongReal for the long
types.
$ gm2 -fiso dice.mod -o dice $ ./dice dice: 5 2 5 3 1 4 2 2 6 3 -5..5: -2 3 -1 3 -2 4 0 -1 5 4 0..999: 674 427 438 368 720
Repeatable sequences
A test or a simulation that must give the same result every time needs
the same random numbers every time. RandomInit sets the seed,
and the same seed starts the same sequence.
MODULE seeded;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM RandomNumber IMPORT RandomInit, Randomize, RandomInt;
PROCEDURE Rolls(label: ARRAY OF CHAR);
VAR
i: CARDINAL;
BEGIN
WriteString(label);
FOR i := 1 TO 10 DO
WriteInt(RandomInt(1, 6), 2)
END;
WriteLn
END Rolls;
BEGIN
RandomInit(2026);
Rolls("seed 2026:");
RandomInit(2026);
Rolls("seed 2026:");
RandomInit(7);
Rolls("seed 7: ");
Randomize;
Rolls("clock: ")
END seeded.
The two runs with seed 2026 roll the same ten numbers, and seed 7 rolls
others. Randomize goes back to a seed from the clock, so
only the last line changes between the two runs of the program. The
sequence for a seed depends on the rand function of the C
library; another system may produce other numbers. The remaining
examples use seed 2026, so that the text can describe their output.
$ gm2 -fiso seeded.mod -o seeded $ ./seeded seed 2026: 2 1 1 3 1 2 6 4 6 3 seed 2026: 2 1 1 3 1 2 6 4 6 3 seed 7: 2 3 3 2 5 6 2 2 1 6 clock: 4 4 3 4 6 6 4 3 1 5 $ ./seeded seed 2026: 2 1 1 3 1 2 6 4 6 3 seed 2026: 2 1 1 3 1 2 6 4 6 3 seed 7: 2 3 3 2 5 6 2 2 1 6 clock: 3 1 4 1 6 2 6 1 5 3
A histogram
Counting many results shows whether a generator is fair. The sum of two dice is not uniform: 7 has six combinations, 2 and 12 only one each.
MODULE histogram;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM RandomNumber IMPORT RandomInit, RandomCard;
CONST
Rolls = 6000;
VAR
counts: ARRAY [2..12] OF CARDINAL;
i, sum, star: CARDINAL;
BEGIN
RandomInit(2026);
FOR sum := 2 TO 12 DO counts[sum] := 0 END;
FOR i := 1 TO Rolls DO
sum := RandomCard(1, 6) + RandomCard(1, 6);
INC(counts[sum])
END;
FOR sum := 2 TO 12 DO
WriteCard(sum, 2); WriteCard(counts[sum], 5); WriteChar(' ');
FOR star := 1 TO counts[sum] DIV 25 DO
WriteChar('*')
END;
WriteLn
END
END histogram.
The array is indexed by the sum itself, from 2 to 12, so no offset is needed. Each star stands for 25 rolls. The expected count for 7 is 6000 × 6/36 = 1000, and for 2 or 12 it is about 167; the counts are close to that, and the bars form the expected triangle.
$ gm2 -fiso histogram.mod -o histogram $ ./histogram 2 148 ***** 3 328 ************* 4 511 ******************** 5 700 **************************** 6 800 ******************************** 7 1028 ***************************************** 8 822 ******************************** 9 651 ************************** 10 505 ******************** 11 333 ************* 12 174 ******
An empty range
The range functions take the random number modulo the size of the range and add the lower bound. They have one special case that is easy to hit: the range from 0 to 0 returns an unrestricted random number.
MODULE ranges;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM RandomNumber IMPORT RandomInit, RandomCard;
PROCEDURE Pick(low, high: CARDINAL): CARDINAL;
BEGIN
IF low = high THEN
RETURN low
END;
RETURN RandomCard(low, high)
END Pick;
VAR
n: CARDINAL;
BEGIN
RandomInit(2026);
FOR n := 2 TO 0 BY -1 DO
WriteString("RandomCard(0, "); WriteCard(n, 0); WriteString(") = ");
WriteCard(RandomCard(0, n), 0); WriteLn
END;
WriteString("RandomCard(5, 5) = "); WriteCard(RandomCard(5, 5), 0); WriteLn;
WriteString("RandomCard(6, 1) = "); WriteCard(RandomCard(6, 1), 0); WriteLn;
WriteString("Pick(0, 0) = "); WriteCard(Pick(0, 0), 0); WriteLn
END ranges.
RandomCard(0, 0) should return 0, but the module uses
(0, 0) as a request for any number, and the same holds for
RandomInt. RandomCard(5, 5) works as expected.
Reversed bounds are not checked and give garbage. Such ranges appear when
the upper bound is computed, for example the last index of a list that
has one element. Pick returns the bound itself when both are
equal; callers must still keep the bounds in order.
$ gm2 -fiso ranges.mod -o ranges $ ./ranges RandomCard(0, 2) = 1 RandomCard(0, 1) = 0 RandomCard(0, 0) = 1442760586 RandomCard(5, 5) = 5 RandomCard(6, 1) = 1933575930 Pick(0, 0) = 0
Reals in a range
A real number in another range is a linear transformation of
RandomReal: multiply by the width of the range and add its
lower end.
MODULE scaled;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM RandomNumber IMPORT RandomInit, RandomReal;
PROCEDURE Uniform(low, high: REAL): REAL;
BEGIN
RETURN low + (high - low) * RandomReal()
END Uniform;
VAR
i: CARDINAL;
x, sum, least, most: REAL;
BEGIN
RandomInit(2026);
sum := 0.0;
least := 100.0;
most := -100.0;
FOR i := 1 TO 100000 DO
x := Uniform(-2.5, 7.5);
sum := sum + x;
IF x < least THEN least := x END;
IF x > most THEN most := x END
END;
WriteString("smallest "); WriteFixed(least, 4, 8); WriteLn;
WriteString("largest "); WriteFixed(most, 4, 8); WriteLn;
WriteString("mean "); WriteFixed(sum / 100000.0, 4, 8); WriteLn
END scaled.
Uniform returns a value from -2.5 to 7.5. A hundred thousand
values come close to both ends and have a mean close to 2.5, the middle of
the range. For integers, RandomInt is better than a scaled
real: the formula low + TRUNC(RandomReal() * FLOAT(n)) gives
low + n, one past the range, when RandomReal
returns exactly 1.0.
$ gm2 -fiso scaled.mod -o scaled $ ./scaled smallest -2.4999 largest 7.4998 mean 2.5023
Shuffling
The Fisher-Yates shuffle puts the elements of an array in random order, with every order equally likely. It walks from the last element to the second and swaps each with a random element at or before it.
MODULE shuffle;
FROM STextIO IMPORT WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM RandomNumber IMPORT RandomInit, RandomCard;
PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER);
VAR
i, j: CARDINAL;
t: INTEGER;
BEGIN
FOR i := HIGH(a) TO 1 BY -1 DO
j := RandomCard(0, i);
t := a[i]; a[i] := a[j]; a[j] := t
END
END Shuffle;
PROCEDURE Show(a: ARRAY OF INTEGER);
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(a) DO
WriteInt(a[i], 3)
END;
WriteLn
END Show;
VAR
cards: ARRAY [0..9] OF INTEGER;
n: CARDINAL;
BEGIN
RandomInit(2026);
FOR n := 0 TO 9 DO cards[n] := n + 1 END;
Show(cards);
Shuffle(cards);
Show(cards);
Shuffle(cards);
Show(cards)
END shuffle.
Shuffle works on an open array, so it shuffles arrays of any
length. The loop stops at index 1, so RandomCard(0, i) never
gets the empty range from the previous section. The second shuffle starts
from the order the first one left.
$ gm2 -fiso shuffle.mod -o shuffle $ ./shuffle 1 2 3 4 5 6 7 8 9 10 8 2 6 5 7 1 9 3 4 10 2 4 10 3 8 9 6 1 5 7
Estimating pi
A Monte Carlo method answers a question by random sampling. Points chosen at random in the unit square fall inside the quarter circle of radius 1 with probability π/4, so four times the share of points inside estimates π.
MODULE montecarlo;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;
FROM RandomNumber IMPORT RandomInit, RandomReal;
PROCEDURE EstimatePi(points: CARDINAL): REAL;
VAR
i, inside: CARDINAL;
x, y: REAL;
BEGIN
inside := 0;
FOR i := 1 TO points DO
x := RandomReal();
y := RandomReal();
IF x * x + y * y <= 1.0 THEN INC(inside) END
END;
RETURN 4.0 * FLOAT(inside) / FLOAT(points)
END EstimatePi;
VAR
count: CARDINAL;
BEGIN
RandomInit(2026);
count := 100;
WHILE count <= 10000000 DO
WriteCard(count, 9);
WriteFixed(EstimatePi(count), 5, 10);
WriteLn;
count := count * 10
END
END montecarlo.
EstimatePi takes two random coordinates per point and counts
the points with x2 + y2 ≤ 1. The
estimate improves slowly: the error shrinks with the square root of the
number of points, so a hundred times more points give one more correct
digit. The whole run takes about three seconds: RandomReal
calls rand eight times, once for each byte of a 64-bit
number, so the generator is not fast.
$ gm2 -fiso montecarlo.mod -o montecarlo
$ ./montecarlo
100 2.96000
1000 3.15600
10000 3.12360
100000 3.13636
1000000 3.13950
10000000 3.14195
A random walk
A random walk moves one step left or right at random. The program draws the position on a line of 21 columns after each step.
MODULE walk;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM RandomNumber IMPORT RandomInit, RandomInt;
CONST
Width = 21;
PROCEDURE ShowAt(at: INTEGER);
VAR
col: INTEGER;
BEGIN
WriteChar('|');
FOR col := 1 TO Width DO
IF col = at THEN WriteChar('o') ELSE WriteChar(' ') END
END;
WriteChar('|');
WriteInt(at, 4);
WriteLn
END ShowAt;
VAR
position, step: INTEGER;
BEGIN
RandomInit(2026);
position := (Width + 1) DIV 2;
ShowAt(position);
FOR step := 1 TO 15 DO
IF RandomInt(0, 1) = 0 THEN DEC(position) ELSE INC(position) END;
ShowAt(position)
END;
WriteString("final position "); WriteInt(position, 0); WriteLn
END walk.
RandomInt(0, 1) works as a coin toss. The walk starts in the
middle column, and 15 steps cannot take it past either edge. Random walks
model the movement of particles, prices and gamblers' purses; on average
the walker stays where it started, but the typical distance from the
start grows with the square root of the number of steps.
$ gm2 -fiso walk.mod -o walk $ ./walk | o | 11 | o | 12 | o | 11 | o | 10 | o | 9 | o | 8 | o | 9 | o | 10 | o | 11 | o | 12 | o | 11 | o | 10 | o | 11 | o | 12 | o | 11 | o | 10 final position 10
Source
In this article we have generated random reals and integers with the GNU
RandomNumber module, repeated sequences with a seed, checked
the distribution with a histogram, avoided the empty-range trap, scaled
reals to a range, shuffled an array, estimated π and simulated a random
walk. The sorting article uses a seeded
generator of its own for test data, and the
math article covers the real functions.
Author
List all Modula-2 tutorials.