Built-in random number generator cannot be used directly for generating 32-bit random number.
Original Reporter info from Mantis: zoran
-
Reporter name: Zoran Vučenović
Original Reporter info from Mantis: zoran
- Reporter name: Zoran Vučenović
Description:
There are three overloaded Random functions in System unit (http://www.freepascal.org/docs-html/current/rtl/system/random.html).
However, neither of these can be used for getting random 32-bit value.
Looking into sources, I see that we have genrand_MT19937 which returns 32-bit pseudo-random number. All three publicly available functions call this functions, but all three cut something from result.
Now the best we can get is Random(High(Longint)), but it returns positive number (so, the best we can get is 31-bit). Or call 64-bit version and cut result to 32-bit -- Random(High(Int64)) and $FFFFFFFF, but it calls genrand_MT19937 twice (and spare two elements of pseudo-random sequence), which should not be needed for 32-bit result.
So, I'm asking for making genrand_MT19937 public (declare it in interface section), or create another function Random32Bit without arguments which will just return what it gets from calling genrand_MT19937.
Additional information:
For 64-bit pseudo-random number, the best I could do is this (it spares three elements of pseudo-random sequence):
function Random64Bit: QWord;
begin
Result := Random(High(Int64)); // this calls genrand_MT19937 twice
if Random < 0.5 then // and this once more
Result := (QWord(1) shl 63) or Result;
end;
Instead of this (spares just two elements of pseudo-random sequence):
function Random64Bit: QWord;
begin
Result := LongWord(genrand_MT19937);
Result := (Result shl 32) + LongWord(genrand_MT19937);
end;
Mantis conversion info:
- Mantis ID: 31633
- Version: 3.1.1