ZetCode

Random numbers in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

Pascal's random generator is a pseudo-random number generator: it produces a deterministic sequence from an internal seed, and the same seed always gives the same sequence. The Random function returns a real in [0, 1) or an integer below a limit, Randomize sets the seed from the clock, and RandSeed exposes the seed directly. This article shows how to draw values, make a run reproducible, build ranges, draw a dice histogram, estimate pi, shuffle an array, generate normally distributed values, and simulate the birthday problem.

Random and Randomize

Random without an argument returns a Double greater than or equal to 0 and less than 1. Random(N) with a positive integer argument returns an integer from 0 to N - 1. Calling Randomize once at the start seeds the generator from the system clock so that different runs normally differ. The Math unit adds RandomRange, which returns a value in a half-open interval.

rng.pas
program rng;
{$mode objfpc}{$H+}

uses Math, SysUtils;

var
  I: Integer;

begin
  Randomize;
  Write('ints:   ');
  for I := 1 to 8 do
    Write(Random(100), ' ');
  WriteLn;

  Write('reals:  ');
  for I := 1 to 5 do
    Write(FormatFloat('0.000', Random), ' ');
  WriteLn;

  Write('range:  ');
  for I := 1 to 5 do
    Write(RandomRange(10, 20), ' ');
  WriteLn;
end.

The integer values are in 0..99, the reals have three printed decimals but full internal precision, and the range values are in 10..19. Randomize does not make the generator cryptographically secure: the sequence is predictable once enough outputs are known, so passwords, tokens, and keys need a different source. For simulations and games, the generator is fast and good enough. The exact values in the output change from run to run; the values shown here came from one run.

$ fpc -gl rng.pas
$ ./rng
ints:   33 27 86 9 10 24 79 65
reals:  0.365 0.469 0.152 0.210 0.096
range:  10 13 19 10 16

Reproducible sequences

RandSeed is a global variable of type LongInt. Assigning it resets the generator to a known state, which makes a run repeatable: simulations can be replayed, tests can compare exact output, and a bug that appears with one seed can be reproduced with the same number. Assigning the same seed twice gives the same sequence again.

seed.pas
program seed;
{$mode objfpc}{$H+}

procedure ShowSequence;
var
  J: Integer;
begin
  for J := 1 to 5 do
    Write(Random(1000), ' ');
  WriteLn;
end;

begin
  RandSeed := 1234;
  Write('first:  ');
  ShowSequence;

  RandSeed := 1234;
  Write('second: ');
  ShowSequence;

  RandSeed := 9999;
  Write('other:  ');
  ShowSequence;
end.

The first two lines are identical because both start from seed 1234; the third line differs. A program that never calls Randomize and never sets RandSeed also starts from a fixed seed, so its sequence repeats in every run. That is convenient for demonstrations but surprising in a game. Randomize seeds from the clock with second or millisecond resolution depending on the platform, so two runs started within the same tick can still produce the same sequence; this happened with the first example when it was run twice in quick succession.

$ fpc -gl seed.pas
$ ./seed
first:  191 497 622 817 437
second: 191 497 622 817 437
other:  823 806 218 748 31

Ranges and bounds

RandomRange(Low, High) returns an integer in Low..High - 1, so RandomRange(10, 20) never returns 20. This half-open convention matches Random(N) and makes it easy to combine ranges without off-by-one errors. A range that crosses zero works as well, because the implementation shifts the result.

range.pas
program range;
{$mode objfpc}{$H+}

uses Math;

var
  I, V, MinV, MaxV: Integer;

begin
  RandSeed := 1;
  MinV := MaxInt;
  MaxV := -MaxInt;
  for I := 1 to 1000 do
  begin
    V := RandomRange(-5, 6);
    if V < MinV then MinV := V;
    if V > MaxV then MaxV := V;
  end;
  WriteLn('min: ', MinV, ', max: ', MaxV);
  WriteLn('RandomRange(10, 20) < 20: ', RandomRange(10, 20) < 20);
end.

After 1000 draws from -5..5 the minimum is -5 and the maximum is 5, which is what a uniform generator should produce. The last line is always true for a correct implementation, and it documents the half-open upper bound. To include 20, call RandomRange(10, 21); to roll a die, use RandomRange(1, 7) or Random(6) + 1.

$ fpc -gl range.pas
$ ./range
min: -5, max: 5
RandomRange(10, 20) < 20: TRUE

A dice histogram

A histogram counts how often each outcome occurs. With 60,000 rolls of a fair die, every face should appear about 10,000 times. The example stores the counts in an array indexed by the face value, draws the roll with Random(6) + 1, and prints each count together with its percentage. A fixed seed makes the numbers reproducible.

dice.pas
program dice;
{$mode objfpc}{$H+}

uses SysUtils;

var
  Counts: array[1..6] of Integer;
  I, Roll: Integer;

begin
  RandSeed := 2026;
  for I := 1 to 6 do
    Counts[I] := 0;

  for I := 1 to 60000 do
  begin
    Roll := Random(6) + 1;
    Inc(Counts[Roll]);
  end;

  for I := 1 to 6 do
    WriteLn(I, ': ', Counts[I], ' (',
      FormatFloat('0.00', Counts[I] / 600), '%)');
end.

The percentages are computed by dividing by 600, because 60,000 rolls divided by 100 percent is 600 rolls per percent. The counts fluctuate around 10,000 by roughly 100, which is the expected statistical noise for this sample size. The array index type 1..6 makes the mapping from face to slot explicit, and Inc(Counts[Roll]) updates the selected element.

$ fpc -gl dice.pas
$ ./dice
1: 10007 (16.68%)
2: 9866 (16.44%)
3: 10022 (16.70%)
4: 9910 (16.52%)
5: 10111 (16.85%)
6: 10084 (16.81%)

Estimating pi

Monte Carlo integration estimates an area by drawing random points and counting how many fall inside it. The unit circle occupies a quarter of the square with corners (0,0) and (1,1), so the fraction of points inside the quarter circle multiplied by 4 estimates pi. The estimate improves slowly: the error shrinks with the square root of the number of samples.

montecarlo.pas
program montecarlo;
{$mode objfpc}{$H+}

uses SysUtils;

var
  I, Inside: Integer;
  X, Y: Double;

begin
  RandSeed := 2026;
  Inside := 0;
  for I := 1 to 1000000 do
  begin
    X := Random;
    Y := Random;
    if X * X + Y * Y <= 1.0 then
      Inc(Inside);
  end;
  WriteLn('inside: ', Inside);
  WriteLn('pi estimate: ', FormatFloat('0.00000', 4.0 * Inside / 1000000));
end.

The test X * X + Y * Y <= 1.0 is the quarter circle of radius one. One million samples gave 785,463 points inside, or 3.14185, which is correct to three decimal places. Doubling the samples only divides the typical error by about 1.41, so this method is used for shapes whose area is hard to compute, not for computing pi to many digits.

$ fpc -gl montecarlo.pas
$ ./montecarlo
inside: 785463
pi estimate: 3.14185

Shuffling an array

The Fisher-Yates shuffle walks the array from the end to the second element, picks a random index from the remaining prefix, and swaps the two elements. Every permutation is equally likely, and the loop performs exactly n - 1 swaps. Picking a random index for every position without shrinking the range, or sorting by random keys, produces biased permutations.

shuffle.pas
program shuffle;
{$mode objfpc}{$H+}

var
  Cards: array[1..10] of Integer;
  I, J, Temp: Integer;

begin
  RandSeed := 42;
  for I := 1 to 10 do
    Cards[I] := I;

  for I := 10 downto 2 do
  begin
    J := Random(I) + 1;
    Temp := Cards[I];
    Cards[I] := Cards[J];
    Cards[J] := Temp;
  end;

  for I := 1 to 10 do
    Write(Cards[I], ' ');
  WriteLn;
end.

At the first iteration I is 10 and J is in 1..10, so the last slot receives any of the ten cards. At the next iteration the range is 1..9, and the card already placed at position 10 is never touched again. The fixed seed 42 produced the permutation 6 1 7 3 10 5 2 9 8 4; a different seed produces a different order.

$ fpc -gl shuffle.pas
$ ./shuffle
6 1 7 3 10 5 2 9 8 4

Normal variates

Random is uniform, but measurements and noise usually follow a normal distribution. The Box-Muller transform turns two independent uniform values into two independent standard normal values: if U1 and U2 are uniform in (0, 1), then Sqrt(-2 Ln U1) Cos(2 Pi U2) is standard normal. The example generates 10,000 values and checks their mean and standard deviation.

normal.pas
program normal;
{$mode objfpc}{$H+}

uses Math, SysUtils;

var
  I: Integer;
  U1, U2, Z, Sum, SumSq: Double;

begin
  RandSeed := 7;
  Sum := 0;
  SumSq := 0;
  for I := 1 to 10000 do
  begin
    U1 := Random;
    U2 := Random;
    Z := Sqrt(-2.0 * Ln(U1)) * Cos(2.0 * Pi * U2);
    Sum := Sum + Z;
    SumSq := SumSq + Z * Z;
  end;
  WriteLn('mean: ', FormatFloat('0.000', Sum / 10000));
  WriteLn('stddev: ', FormatFloat('0.000', Sqrt(SumSq / 10000)));
end.

The sample mean is close to 0 and the sample standard deviation is close to 1, as expected. Ln(U1) is negative because U1 is below one, so the negation makes the square root argument positive. Random can return exactly 0, although the probability is tiny; a production routine guards against the logarithm of zero by drawing again or by adding a small offset.

$ fpc -gl normal.pas
$ ./normal
mean: -0.004
stddev: 0.995

The birthday problem

The birthday problem asks how likely it is that at least two people in a group share a birthday. With 23 people the answer is slightly more than 50 percent, which most people find surprisingly high. A simulation draws 23 days from 1..365 for each trial, marks the days in a Boolean array, and counts a hit when a day is drawn twice.

birthday.pas
program birthday;
{$mode objfpc}{$H+}

uses SysUtils;

const
  People = 23;
  Trials = 10000;

var
  Taken: array[1..365] of Boolean;
  T, P, Day: Integer;
  Shared, Hits: Integer;

begin
  RandSeed := 2026;
  Hits := 0;
  for T := 1 to Trials do
  begin
    for Day := 1 to 365 do
      Taken[Day] := False;
    Shared := 0;
    for P := 1 to People do
    begin
      Day := Random(365) + 1;
      if Taken[Day] then
        Inc(Shared);
      Taken[Day] := True;
    end;
    if Shared > 0 then
      Inc(Hits);
  end;
  WriteLn('trials: ', Trials);
  WriteLn('shared birthday: ', Hits);
  WriteLn('probability: ', FormatFloat('0.0000', Hits / Trials));
end.

The simulation gives 0.5005, close to the theoretical 0.5073. The inner loop clears all 365 flags for each trial, which costs more than the drawing itself; a smaller program could use a set of days and reset it in one assignment. Leap years are ignored, and the model assumes that all birthdays are equally likely, which is close enough for the demonstration.

$ fpc -gl birthday.pas
$ ./birthday
trials: 10000
shared birthday: 5005
probability: 0.5005

Next steps

The enumerations and sets article shows how to track drawn values with a set, and the scientific simulations article uses random walks and seeded runs. The date and time article explains the clock behind Randomize, and the sorting article compares the library sorts that can order simulated data.

Source

Free Pascal: Random

Free Pascal: RandSeed

Fisher-Yates shuffle on Wikipedia

In this article we drew integer and real values, seeded the generator for reproducible runs, used half-open ranges, counted dice outcomes, estimated pi, shuffled an array, generated normal values, and simulated shared birthdays. The series continues with command-line arguments in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.