Random Numbers in Pascal
Here’s the Pascal translation of the random numbers example:
Our program demonstrates the generation of random numbers in Pascal. Here’s the full source code:
program RandomNumbers;
uses
SysUtils, Math;
var
i: Integer;
f: Double;
begin
// For example, Random(100) returns a random integer n,
// 0 <= n < 100.
Write(Random(100), ',');
WriteLn(Random(100));
// Random returns a real number f,
// 0.0 <= f < 1.0.
WriteLn(Random);
// This can be used to generate random floats in
// other ranges, for example 5.0 <= f' < 10.0.
Write((Random * 5) + 5, ',');
WriteLn((Random * 5) + 5);
// If you want a known seed, use RandSeed.
// This is similar to creating a new random source with a seed.
RandSeed := 42;
Write(Random(100), ',');
WriteLn(Random(100));
// Using the same seed will produce the same sequence of random numbers.
RandSeed := 42;
Write(Random(100), ',');
WriteLn(Random(100));
end.
To run the program, save it as random_numbers.pas
and compile it using a Pascal compiler like Free Pascal:
$ fpc random_numbers.pas
$ ./random_numbers
The output might look something like this:
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49
Note that some of the generated numbers may be different when you run the sample.
In Pascal, the Random
function from the System
unit provides pseudorandom number generation. The Random
function without arguments returns a real number between 0 and 1, while Random(n)
returns an integer between 0 and n-1.
To set a seed for the random number generator, we use the RandSeed
variable. This is similar to creating a new random source with a seed in other languages.
Pascal’s standard library doesn’t provide as many random number generation options as some other languages, but these basic functions are sufficient for many use cases. For more advanced random number generation, you might need to implement your own algorithms or use additional libraries.