Wednesday 27 February 2019

New in Rio: custom PRNG

I don't know if anyone noticed, but there is something new in the System unit of Delphi 10.3 Rio that is not documented yet.

In Rio, if you want to improve the default pseudo random number generator (PRNG), you can now supply your own 32 bit random function. There is a procedural variable, Random32Proc of type function: UInt32, to which you can assign your own random function. Random will call this function to get a new random value instead of the default function.

The default setting of this variable is System.DefaultRandom32. This is the same as the old Delphi PRNG.

Because your new function may need a different way to set the random seed too, there is something similar for Randomize: RandomizeProc.

Here is the corresponding part of System.pas:

{ random functions }

  TRandom32Proc = function: UInt32;
  TRandomizeProc = procedure(NewSeed: UInt64);

function DefaultRandom32: UInt32;
procedure DefaultRandomize(NewSeed: UInt64);

  Random32Proc: TRandom32Proc = DefaultRandom32;
  RandomizeProc: TRandomizeProc = DefaultRandomize;

procedure Randomize;

function Random(const ARange: Integer): Integer; overload;
function Random: Extended; overload;

I tried this with the XorShift implementation in my DelphiBigNumbers GitHub repository and it worked as expected.

Much fun with this!

No comments:

Post a Comment