ZetCode

Ada random numbers

last modified November 23, 2026

Ada does not put a random function in the language itself. Two generic packages in Ada.Numerics provide pseudo-random values instead: Float_Random produces real values between zero and one, and Discrete_Random produces values of a discrete type such as a range of integers or an enumeration. Both are driven by a Generator object that a program creates, seeds, and reuses. This article seeds a generator, scales its values into a range, rolls dice, shuffles an array, and counts the faces of six thousand rolls in a histogram.

A first random value

Ada.Numerics.Float_Random is not generic; its Random function always returns a value of the subtype Uniformly_Distributed, which lies in the range zero to one, including zero but not one. A Generator holds the state of the sequence, and Reset without a second argument seeds it from a default value that differs between runs, so two runs of the program see different numbers.

rand_float.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;

procedure Rand_Float is
   Gen : Generator;
begin
   Reset (Gen);
   for I in 1 .. 3 loop
      Put_Line (Float'Image (Random (Gen)));
   end loop;
end Rand_Float;

The default Float'Image prints the values in scientific notation with six significant digits, which is why the three numbers appear as 2.45303E-01 and so on. The digits themselves change on every run, because Reset (Gen) picks a different starting state each time. The sequence is not truly random, but it is long enough and uniform enough for simulations, games, and test data.

$ gnatmake -gnat2022 -gnatwa rand_float.adb
$ ./rand_float
 2.45303E-01
 7.47839E-01
 6.35309E-01

The same seed, the same sequence

A generator can also be seeded explicitly. Reset (Gen, 42) puts the generator into a fixed state, so the values that follow are the same on every run with the same GNAT generator. This is how a test produces repeatable data and how a game replays a level from a recorded seed.

rand_seed.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;

procedure Rand_Seed is
   Gen : Generator;
   A, B, First_A, First_B : Float;
begin
   Reset (Gen, 42);
   First_A := Random (Gen);
   First_B := Random (Gen);
   Put_Line ("first run  =" & Float'Image (First_A) &
             "," & Float'Image (First_B));

   Reset (Gen, 42);
   A := Random (Gen);
   B := Random (Gen);
   Put_Line ("second run =" & Float'Image (A) &
             "," & Float'Image (B));
   Put_Line ("same values =" &
             Boolean'Image (A = First_A and then B = First_B));
end Rand_Seed;

The first two values are saved before the generator is reset, and the second pair is compared with them. Both runs start from the same state, so the pairs are equal and the last line prints TRUE. Note that Reset discards the current state entirely; it does not continue the old sequence. The seed is an Integer, so any number can be used, including zero and negative values.

$ gnatmake -gnat2022 -gnatwa rand_seed.adb
$ ./rand_seed
first run  = 6.87270E-01, 8.98271E-01
second run = 6.87270E-01, 8.98271E-01
same values =TRUE

Scaling to a range

Most programs need a value between some minimum and maximum, not between zero and one. A simple linear transformation does the job: multiply the random value by the width of the interval and add the lower bound. The next program picks a temperature between 18 and 24 degrees and a score between 60 and 100. The score uses Float'Floor before converting to Integer, because a conversion rounds to the nearest integer rather than truncating it.

rand_range.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;

procedure Rand_Range is
   package Temp_IO is new Ada.Text_IO.Float_IO (Float);
   Gen : Generator;
   Temp : Float;
   Score : Integer;
begin
   Reset (Gen, 7);
   Temp := 18.0 + Random (Gen) * 6.0;
   Score := 60 + Integer (Float'Floor (Random (Gen) * 41.0));
   Put ("temperature = ");
   Temp_IO.Put (Temp, Fore => 1, Aft => 2, Exp => 0);
   New_Line;
   Put_Line ("score = " & Integer'Image (Score));
end Rand_Range;

The temperature is 18.0 plus a fraction of the six-degree width, so it can never reach 24.0. The score formula multiplies by 41.0, floors the result to an integer from 0 to 40, and adds 60, which gives every score from 60 to 100 with equal probability. Without Float'Floor, a value such as 5.7 would be rounded up to 6 and the result could leave the intended range. Float_IO prints the temperature with two decimal places, and Integer'Image leaves a space where a minus sign could go, so the score line has two spaces after the equals sign.

$ gnatmake -gnat2022 -gnatwa rand_range.adb
$ ./rand_range
temperature = 21.23
score =  85

A discrete type

When the values are integers, enumeration literals, or any other discrete type, Ada.Numerics.Discrete_Random is a better fit than scaling a float and converting it. It is a generic package with one formal parameter, the result subtype, and its Random function returns a value of that subtype without any conversion. The next program instantiates it for the six faces of a die.

rand_discrete.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Rand_Discrete is
   subtype Die_Face is Integer range 1 .. 6;
   package Die_Random is new Ada.Numerics.Discrete_Random (Die_Face);
   Gen : Die_Random.Generator;
   Face : Die_Face;
begin
   Die_Random.Reset (Gen, 11);
   for I in 1 .. 12 loop
      Face := Die_Random.Random (Gen);
      Put (Die_Face'Image (Face));
   end loop;
   New_Line;
end Rand_Discrete;

The generator type and the operations come from the instance, so they are called as Die_Random.Reset and Die_Random.Random. Every value is guaranteed to be a valid Die_Face; there is no seventh value and no zero. The same seed produces the same twelve rolls, which makes the output below repeatable. Each result type needs its own instance, and each instance declares its own generator type, so the generator objects are not interchangeable between instances.

$ gnatmake -gnat2022 -gnatwa rand_discrete.adb
$ ./rand_discrete
 4 4 1 6 6 4 6 1 2 6 5 1

Shuffling an array

A shuffle is a loop that swaps each position with a randomly chosen position from the part of the array that has not been fixed yet. This is the Fisher–Yates algorithm. It walks from the first index up to the last but one, draws an index J between I and the last index, and exchanges the two elements. The random offset is computed with Float'Floor, so it always lands inside the remaining part.

rand_shuffle.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;

procedure Rand_Shuffle is
   type Deck_Type is array (1 .. 10) of Integer;
   Starting : constant Deck_Type := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   Cards : Deck_Type := Starting;
   Gen : Generator;
   J, Tmp : Integer;
begin
   Reset (Gen, 2026);
   for I in Cards'First .. Cards'Last - 1 loop
      J := I + Integer (Float'Floor
             (Random (Gen) * Float (Cards'Last - I + 1)));
      Tmp := Cards (I);
      Cards (I) := Cards (J);
      Cards (J) := Tmp;
   end loop;
   for Card of Cards loop
      Put (Integer'Image (Card));
   end loop;
   New_Line;
end Rand_Shuffle;

Starting and Cards share the named type Deck_Type, so the initial value can be copied with a simple assignment. The shuffle changes only Cards. Each pass fixes one more position at the front, and the last position follows from the rest, so the output is a permutation of the original ten values. Because the seed is fixed, the same deal can be produced again; changing the seed produces a different one.

$ gnatmake -gnat2022 -gnatwa rand_shuffle.adb
$ ./rand_shuffle
 7 9 5 1 10 3 4 2 6 8

An applied example: a histogram

A simulation usually repeats the same draw thousands of times and counts the results. The last program rolls a die six thousand times, stores the counts in an array indexed by the face, and prints a bar for every face. One star stands for a hundred rolls, so a fair die produces about ten stars per face.

rand_histogram.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Rand_Histogram is
   subtype Die_Face is Integer range 1 .. 6;
   package Die_Random is new Ada.Numerics.Discrete_Random (Die_Face);
   Counts : array (Die_Face) of Natural := [others => 0];
   Gen : Die_Random.Generator;
   Face : Die_Face;
   Rolls : constant := 6_000;
begin
   Die_Random.Reset (Gen, 2026);
   for I in 1 .. Rolls loop
      Face := Die_Random.Random (Gen);
      Counts (Face) := Counts (Face) + 1;
   end loop;

   for F in Die_Face loop
      Put (Die_Face'Image (F) & ": " &
           Natural'Image (Counts (F)) & " ");
      for Star in 1 .. Counts (F) / 100 loop
         Put ("*");
      end loop;
      New_Line;
   end loop;
end Rand_Histogram;

The array is indexed by the subtype itself, so Counts (Face) is always inside its bounds and no range check can fail. The inner loop uses integer division, which drops the remainder: a face with 991 hits gets nine stars, and a face with 1000 gets ten. The counts differ from exactly one thousand because each roll is independent, but with six thousand rolls they stay close to it.

$ gnatmake -gnat2022 -gnatwa rand_histogram.adb
$ ./rand_histogram
 1:  1000 **********
 2:  991 *********
 3:  1003 **********
 4:  1010 **********
 5:  982 *********
 6:  1014 **********

Next steps

The series continues with interfacing with C, where a program calls functions from a C library and exports an Ada subprogram back to C. The arrays article explains the indexed arrays used for the counts, and text output covers the field widths that format numeric reports.

Source

Ada Reference Manual: Random Number Generation

GNAT User's Guide

In this article we have seeded a floating-point generator, reproduced a sequence from the same seed, scaled values into an interval with Float'Floor, drawn from a discrete subtype, shuffled an array, and counted six thousand rolls. The scalar types article explains the subtypes that a discrete generator is instantiated with.

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 Ada tutorials.