Delphi compatible LCG Random

From Lazarus wiki
Revision as of 14:42, 26 March 2017 by Thaddy (talk | contribs) (→‎Delphi compatible pseudo-random number generator)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Delphi compatible random numbers

Many Freepascal programmers also maintain a sourcecode in Delphi.
Even if you have moved to Freepascal from Delphi you may have data that relies on Delphi's Random.
Here are compatible routines that generate Delphi-identical pseudo-random numbers:

unit drandom;
// Delphi compatible LCG random number generator routines for Freepascal.
// (c)2017, Thaddy de Koning. Use as you like
// Algorithm, Delphi multiplier and increment taken from:
// https://en.wikipedia.org/wiki/Linear_congruential_generator
// The default Delphi RandomSeed is determined as zero.
{$mode objfpc}{$H+}

interface

function DelphiRandom: Double; overload;inline;
function DelphiRandom(range:integer):integer;overload;inline;

implementation

function IM:dword;inline;
begin
  RandSeed := RandSeed * 134775813  + 1;
  Result := RandSeed;
end;

function DelphiRandom: Double; overload;inline;
begin
  Result := IM * 2.32830643653870e-10;
end;

function DelphiRandom(range:integer):integer;overload;inline;
begin
  Result := IM * range shr 32;
end;

end.