delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/18/06:46:25

Sender: crough45 AT amc DOT de
Message-Id: <97Aug18.123649gmt+0100.17027@internet01.amc.de>
Date: Mon, 18 Aug 1997 11:40:37 +0100
From: Chris Croughton <crough45 AT amc DOT de>
Mime-Version: 1.0
To: xyy AT infonie DOT be
Cc: djgpp AT delorie DOT com
Subject: Re: True random numbers.

Zampelli Stiphane wrote:

>  Can anyone show me a example with srandom, rand, and random 
> functions in order to use *true* random numbers ?

You can't get true random numbers from any software method.
The best source of true randomness is a Brownian Motion input
device (a really hot cup of tea is a good source of Brownian
motion), but you need the hardware to provide the input.  Some
Unix systems have a device called /dev/random which uses other
'random' events like the intervals between keystrokes and the
time between comm port characters, but there's nothing like 
that on DOS that I know of.

In order to use the DJGPP pseudo-random functions, just call
srandom with an input 'seed'.  Often the time function is used
for this, but it only gives the time in seconds which is not 
exactly random.  Then call random() to get each (32 bit) number,
optionally taking it modulo the range (so to get numbers between
0 and 9 do % 10):

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

int main()
{
  int i;
  srandom(time(NULL));
  for (i = 0; i < 10; i++)
    printf("%ld\n", random() % 10);
}

Chris C

- Raw text -


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