ftp.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/11/30/06:41:27

Date: Sat, 30 Nov 1996 11:24:16 GMT
Message-Id: <199611301124.LAA09903@mailhost.sm.ic.ac.uk>
Mime-Version: 1.0
To: djgpp AT delorie DOT com
From: p DOT dixon AT ic DOT ac DOT uk (Paul Dixon)
Subject: Random numbers ...

>Anyway, here's an example of the correct way to use
>random()...
>
> ... header stuff cut out .....
>
>    while ( tolower( getchar( ) ) != 'q' )
>    {
>        r = random( ) % 501;	   /* 0 to 500 */
>        printf( "%d", r );
>    }

I hate to say this, but it is NOT generally advisable to use MODULUS to 
force a random number into a specified range if you really care about the 
quality of the random numbers. Depending on the exact modulus used (N = 501 
above) you may get a 'random' sequence that repeats very often (in worst 
case once every N shots!) - essentially the random number generator is being 
truncated to a log2(N) bit generator instead of 32 bit. Also the low order 
bits of some random number generators are much _less_ random than the high 
order ones ... (I confess I havent read the GNU random() source to check if 
this applies)

If you need a sequence guaranteed to remain 'random' for as long as possible 
You really need to bite the bullet and do a divide ... if you dont mind the 
delay in floating point conversion the ideal is something like

         double modulus = (double)(RAND_MAX) / 500.;
         r = (int)floor((double)random() / modulus);

Using double to ensure mantissa >> 32 bits to ensure no loss of random() 
bits, scale to correct range, truncate to integer.
------------------------------------------------------------------------
Paul Dixon                            
Software Engineer, Dept of Paediatrics     Telephone: (+44) 171 725 6258
St Mary's Hospital Medical School          Fax:       (+44) 171 725 6284
Norfolk Place, London W2 1PG, UK           Email:       p DOT dixon AT ic DOT ac DOT uk

A Constituent College of 
                    Imperial College of Science, Technology and Medicine
------------------------------------------------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019