www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/11/02/00:44:31

Date: Wed, 2 Nov 94 12:17:18 JST
From: Stephen Turnbull <turnbull AT shako DOT sk DOT tsukuba DOT ac DOT jp>
To: cspt AT ludens DOT elte DOT hu
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: Is it random number sequence?

   Date: Tue, 01 Nov 1994 16:06:54 +0100
   From: Csizmadia Peter <cspt AT ludens DOT elte DOT hu>

   int main(int argc, char* argv[])
   {
      int i;
      srand(atoi(argv[1]));
      for(i=0; i<30; ++i)
	 printf(" %d", rand()&3);
      putchar('\n');
   }
	   This simple program produces the following "random number sequence" 
   for any seed number:
    1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2

	   Is it the normal behavior of the rand() function in GNU C?

Using random number generators you haven't coded yourself is often
rather dangerous.  The method you use is one of the best ways to get a
highly nonrandom sequence out of a poorly chosen pseudo-random number
generator; they often do a pretty bad job on the low order bits.
Better to use

        printf(" %d", (rand()>>16)&3);

    This is what I got on Linux, haven't tried DJGPP yet.

turnbull:~$ a.out 1
 1 0 1 2 1 1 2 1 3 0 1 1 3 2 1 1 3 0 2 0 0 1 0 0 3 1 3 3 0 1
turnbull:~$ a.out 1
 1 0 1 2 1 1 2 1 3 0 1 1 3 2 1 1 3 0 2 0 0 1 0 0 3 1 3 3 0 1
turnbull:~$ a.out 2
 0 1 1 3 2 2 1 2 3 3 0 1 0 1 0 2 2 2 1 1 2 3 1 0 2 1 2 1 1 0
turnbull:~$ a.out 3
 2 2 0 0 3 0 0 3 2 3 0 2 2 0 0 3 0 1 1 1 1 1 2 0 1 1 0 2 2 3
turnbull:~$ a.out 4
 1 3 0 1 0 1 3 0 2 2 3 2 3 3 3 0 3 3 0 2 3 3 3 0 0 1 3 0 3 2
turnbull:~$ a.out 5
 3 0 3 2 1 3 2 1 1 2 3 3 1 2 3 1 1 2 0 2 2 1 0 0 3 1 1 1 0 1

- Raw text -


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