www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/11/02/18:54:49

Date: Wed, 2 Nov 1994 09:03:07 -0800
From: elf AT netcom DOT com (Marc Singer)
To: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: Random Number Generators

>    int main(int argc, char* argv[])
>    {
>       int i;
>       srand(atoi(argv[1]));
>       for(i=0; i<30; ++i)
> 	 printf(" %d", rand()&3);
>       putchar('\n');
>    }
> 
>         printf(" %d", (rand()>>16)&3);
> 

If the authors of these pseudo-random number code fragments are
interested, my research has shown that neither of these techniques is
very good for selecting uniform deviates (as they are sometimes
called).  In fact, it is generally not a good idea to select bits from
a sequence of random numbers because you violate the foundation of the
number generator.  They generate random sequences of integers, but not
necessarily random sequences of bits.

You would do much better to partitioning the random number space:

  deviate = rand ();
  if (deviate < RAND_MAX/3)
     result = 0;
  else if (deviate > (RAND_MAX*2)/3)
     result = 2;
  else
     result = 1;

Granted, this is an imperfect partition, but it will more closely
generate a sequence with a random distribution of 0's, 1's and 2's.

Marc Singer
elf AT netcom DOT com

- Raw text -


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