[fpc-pascal] Better random numbers ?

Michalis Kamburelis michalis at camelot.homedns.org
Mon Feb 27 00:03:12 CET 2006

A.J. Venter wrote:
> Hi, I am using standard run of the mill randomize/random() calls in a program 
> to generate random numbers, used in turn to select random data which is fed 
> into another program.
> (All this just to create a multi-language enabled module structure eh)
> Well there is just one little problem, on the commandline it works fine, just 
> about every single call gives a different result, or different enough.
> But when run from inside my other app (where it is threaded) and where I 
> cannot proceed until I have at least the first 5 non-repeating values, it 
> doesn't work so great, I have to call the program an average of 40 times 
> before the value changes - I presume because randomize gets it's seed from 
> the clock and that is how long it takes for the whichever value it uses to 
> update.
> So is there a better way I can do this ? Some way of getting a more frequently 
> updated random seed ? I am talking literally every few milliseconds here.

I think that this problem is more-or-less unavoidable when you want to 
really call Randomize/Random inside the program that is called very often.

The proper solution is to use some system-wide generator, that doesn't 
have to be initialized every time you initialize your program. On Unix, 
just read /dev/urandom, this should return pseudo-random numbers. On 
Windows I guess that you will have to do something like that on your own 
(e.g. write a program in FPC that runs as a service and can be queried 
for random numbers). (Or you can use Cygwin routines to read Cygwin's 
/dev/urandom --- never done it, but it should be possible).

Some other workaround that comes to my mind is to do something like
   RandSeed := RandSeed * getpid;
This way you increase chances that your RandSeed is different for 
different processes, since they will most probably get different 
(usually successive) pids. Probably there is some equivalent to "getpid" 
on Windows.

Hope this helps.


More information about the fpc-pascal mailing list