Search code examples
delphirandomuniform-distribution

How generate uniformly distributed random numbers between 0 and 1, in Delphi


In Matlab this function

r = rand(5)

Result:

r =

0.8147    0.0975    0.1576    0.1419    0.6557
0.9058    0.2785    0.9706    0.4218    0.0357
0.1270    0.5469    0.9572    0.9157    0.8491
0.9134    0.9575    0.4854    0.7922    0.9340
0.6324    0.9649    0.8003    0.9595    0.6787

is used to generate a 5-by-5 matrix of uniformly distributed random numbers between 0 and 1.

What is the equivalent function in Delphi?


Solution

  • There is no standard Delphi RTL function that will generate a matrix or any other collection of random numbers.

    There is however a Random function which you use to generate a single, random number. You simply need to call this as many times as needed to generate the numbers to initialise whatever collection of random numbers you need.

    In Delphi a 5x5 matrix could be represented in a number of ways, one of which might be a simple 2 dimensional array which could be initialised in a simple loop:

    var
      x, y: Integer;
      r: array[0..4, 0..4] of Double;
    begin
      for x := 0 to 4 do
        for y := 0 to 4 do
          r[x][y] := Random;
    
      // etc to work with the matrix (array)...
    
    end;
    

    As with most programming languages/runtimes, by default this will produce the same sequence of random numbers every time you run the program. To change the "seed" and get a different sequence you can either call Randomize or set the RandSeed variable (you will get the same sequence of numbers for a given value of RandSeed).

    The Random function returns a random value between 0.0 and 1.0, sampled from the uniform distribution.

    The pseudo-random number generator (PRNG) used by Delphi is a simple linear congruential generator, very basic and not with very good properties as a PRNG. Matlab uses much better PRNG, its default is Mersenne Twister. If the quality of the pseudo random numbers matters to you then you would need to pick a specific algorithm and either implement it yourself or find it in a suitable library, of which there are plenty.