Random Numbers in Ada
Ada’s Ada.Numerics.Float_Random
and Ada.Numerics.Discrete_Random
packages provide pseudorandom number generation.
with Ada.Text_IO;
with Ada.Numerics.Float_Random;
with Ada.Numerics.Discrete_Random;
procedure Random_Numbers is
use Ada.Text_IO;
package Random_Int is new Ada.Numerics.Discrete_Random (Integer);
Gen : Ada.Numerics.Float_Random.Generator;
Int_Gen : Random_Int.Generator;
begin
-- For example, Random_Int.Random returns a random Integer n,
-- 0 <= n < 100.
Random_Int.Reset(Int_Gen);
Put(Random_Int.Random(Int_Gen, 0, 99)'Image & ",");
Put_Line(Random_Int.Random(Int_Gen, 0, 99)'Image);
-- Ada.Numerics.Float_Random.Random returns a Float f,
-- 0.0 <= f < 1.0.
Ada.Numerics.Float_Random.Reset(Gen);
Put_Line(Ada.Numerics.Float_Random.Random(Gen)'Image);
-- This can be used to generate random floats in
-- other ranges, for example 5.0 <= f' < 10.0.
Put(Float'Image((Ada.Numerics.Float_Random.Random(Gen) * 5.0) + 5.0) & ",");
Put_Line(Float'Image((Ada.Numerics.Float_Random.Random(Gen) * 5.0) + 5.0));
-- If you want a known seed, you can use Reset with a specific seed value.
Ada.Numerics.Float_Random.Reset(Gen, 42);
Random_Int.Reset(Int_Gen, 1024);
Put(Random_Int.Random(Int_Gen, 0, 99)'Image & ",");
Put_Line(Random_Int.Random(Int_Gen, 0, 99)'Image);
-- Using the same seed will produce the same sequence of random numbers.
Ada.Numerics.Float_Random.Reset(Gen, 42);
Random_Int.Reset(Int_Gen, 1024);
Put(Random_Int.Random(Int_Gen, 0, 99)'Image & ",");
Put_Line(Random_Int.Random(Int_Gen, 0, 99)'Image);
end Random_Numbers;
To run the program, save it as random_numbers.adb
and use the Ada compiler (e.g., GNAT):
$ gnatmake random_numbers.adb
$ ./random_numbers
68, 56
8.09022814E-01
5.84012508E+00, 6.93705630E+00
94, 49
94, 49
Some of the generated numbers may be different when you run the sample.
See the Ada Reference Manual, specifically the Ada.Numerics.Float_Random
and Ada.Numerics.Discrete_Random
packages, for references on other random quantities that Ada can provide.
In Ada, we use separate packages for generating random floating-point numbers (Ada.Numerics.Float_Random
) and random integers (Ada.Numerics.Discrete_Random
). The Discrete_Random
package is generic and needs to be instantiated with the desired integer type.
Unlike the original example, Ada doesn’t provide a built-in PCG (Permuted Congruential Generator). Instead, we demonstrate how to use a specific seed to get reproducible random sequences, which is conceptually similar to creating a new source with a known seed.