Delphi: RandomizeIfNeeded
Posted by jpluimers on 2014/10/07
Calling Randomize too often can make your Random numbers even less random.
Sometimes having the Randomize call in a unit initialization section is not practical.
Hence this little method that I think I first wrote back in the Turbo Pascal days:
procedure RandomizeIfNeeded();
begin
if RandSeed = 0 then
Randomize();
end;
–jeroen
This entry was posted on 2014/10/07 at 06:00 and is filed under Delphi, Delphi 1, Delphi 2, Delphi 2005, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi 3, Delphi 4, Delphi 5, Delphi 6, Delphi 7, Delphi 8, Delphi for PHP, Delphi x64, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Development, Pascal, Software Development, Turbo Pascal.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Kevin G. McCoy said
Just put Randomize in an initialization block somewhere. It does not matter how many times you call it on startup; It only matters if you call it repeatedly between generating random numbers. As others pointed out, you should use another algorithm if you want good quality random numbers. See Schneier’s Applied Cryptography book for some good ones.
jpluimers said
Indeed non both cases: Don’t call Randomize in between obtaining Random numbers, creating Delphi’s random number generator is certainly for from any cryptographically secure PRNG.
Jim McKeeth said
@David: Check out this article where Delphi’s Random was compared to Random.org output. It actually did really good.
But that doesn’t make it a CSPRNG.
David Heffernan said
@Jim That article is bogus. LCGs are well known to be poor. This is well documented.
David Heffernan said
Calling Randomize at start up is fine in principle, but you shouldn’t use Randomize or Random because they are rather hopeless. Very poor PRNG, and not threadsafe. It’s 2014.
Klaus said
Why should “having the Randomize call in a unit initialization section is not practical”?
Thanks for futher enlightment!
Regards, Klaus
Jim McKeeth said
I don’t think he is saying it isn’t practical as a rule, but just that there may be times it isn’t practical. Perhaps there are multiple units that want to call Randomize in the initialization section, although that probably won’t change the quality of the randomness.