Difference between revisions of "Delphi compatible LCG Random"
From Free Pascal wiki
Jump to navigationJump to searchLine 15: | Line 15: | ||
function DelphiRandom: extended; overload;inline; | function DelphiRandom: extended; overload;inline; | ||
− | function DelphiRandom(range:longint):longint;overload;inline; | + | function DelphiRandom(const range:longint):longint;overload;inline; |
implementation | implementation | ||
Line 30: | Line 30: | ||
end; | end; | ||
− | function DelphiRandom(range:longint):longint;overload;inline; | + | function DelphiRandom(const range:longint):longint;overload;inline; |
begin | begin | ||
Result := IM * range shr 32; | Result := IM * range shr 32; |
Revision as of 15:32, 26 March 2017
Delphi compatible random numbers
Many Freepascal programmers also maintain sourcecode in Delphi.
Even if you have moved to Freepascal from Delphi you may have data that relies on Delphi's Random.
Here are cross-platform functions 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}
interface
function DelphiRandom: extended; overload;inline;
function DelphiRandom(const range:longint):longint;overload;inline;
implementation
function IM:cardinal;inline;
begin
RandSeed := RandSeed * 134775813 + 1;
Result := RandSeed;
end;
function DelphiRandom: extended; overload;inline;
begin
Result := IM * 2.32830643653870e-10;
end;
function DelphiRandom(const range:longint):longint;overload;inline;
begin
Result := IM * range shr 32;
end;
end.