delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/17/14:38:22

From: mert0407 AT sable DOT ox DOT ac DOT uk (George Foot)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Random numbers...
Date: Sat, 16 Aug 1997 21:21:04 GMT
Organization: [posted via] Easynet Group PLC
Lines: 53
Message-ID: <33f61681.535645@news.easynet.co.uk>
References: <01bcaa71$4c08c200$0d5e4ec2 AT xyy>
NNTP-Posting-Host: foot.easynet.co.uk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

On 16 Aug 1997 18:29:34 GMT, "Zampelli Stéphane" <xyy AT infonie DOT be>
wrote:

>I still can't obtain truly random numbers with the srand(), random(), and
>rand() functions, because, whatever the seed number i put in srand(), it is
>_always the same results.
>
>What can i do about it ?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (void) {
 int x;

 srand(time(NULL));
 rand();

 for (x = 0; x < 10; x++) printf("%d\n",rand());

 return 0;
}

Explanation:

time(NULL) returns a number derived from the system's clock. This will
normally be different each time the code is executed. Passing this to
srand as the seed will mean that to all intents and purposes each time
your program is run a different pseudo-random sequence is issued.

The dummy call to rand() is there to discard the first value, which is
in fact equal to the value of time, and so is rather predictable.

For further information on the time function type `info libc a time'.

If you run this program twice very quickly (in the same second?) it
will give the same sequence of numbers. In the unlikely event that
this is a problem, you could do something more fancy like (untested,
sorry, but you'll get the idea):

void seed_rand() {
 int x,y;
 x = clock();
 y = time(NULL);
 while (y==time(NULL));
 srand(clock()-x+time(NULL));
}

#including the appropriate headers of course.

-- 
george DOT foot AT merton DOT oxford DOT ac DOT uk

- Raw text -


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