Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

What is better to generate random numbers then rand()?

0 views
Skip to first unread message

CLEAVEAGE

unread,
Jul 23, 2003, 7:41:50 PM7/23/03
to
I am using rand() to generate some random integers that I will need in my
program, it works fine, accept that every time the program runs it returns
the same series of random numbers. I thought rand() used some type of timing
function to ensure it would not return the same series each time. What would
I guy need to do to make rand do that, or does anybody have some example
rand function available. Thanks


Scott McPhillips

unread,
Jul 23, 2003, 9:04:57 PM7/23/03
to

No, you are supposed to use some type of timing function to ensure it
will not return the same series each time. The help page for rand()
shows you how.

--
Scott McPhillips [VC++ MVP]

J.N.J.

unread,
Jul 24, 2003, 3:34:50 AM7/24/03
to
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) ); // YOU SHOULD INITIALIZE SEED !!!!

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}

Moreover, if you develop multi-thread application and generate random
numbers in many threads, then you need to use srand() in each thread! In
this case you would need to think about other function than time() for
initial seed, as it measures time with 1 sec precision. And if you start two
or more threads within 1sec, than you again will receive identical
pseudo-random numbers generated.

I'd suggest using QueryPerformanceCounter() in this case.

"CLEAVEAGE" <iamcl...@shaw.ca> сообщил/сообщила в новостях следующее:
news:23FTa.496104$3C2.13...@news3.calgary.shaw.ca...

John Smith

unread,
Jul 24, 2003, 4:40:57 AM7/24/03
to
Furthermore, the documentation clearly states that you have to call "srand"
for EACH thread that calls "rand", otherwise all threads will generate
EXACTLY the same sequence (been there myself...). You could do something
like "srand(GetTickCount() * GetCurrentThreadId())" at the beginning of each
thread to generate as much as possible a random sequence.

"Scott McPhillips" <scot...@mvps.org> wrote in message
news:3F1F30B9...@mvps.org...

Wolfgang

unread,
Jul 24, 2003, 6:17:59 AM7/24/03
to
Hi,
you can take a look at CryptGenRandom(). Look at http://msdn.microsoft.com
for the includes and how to use this function as you have to follow a
certain "protocol" to get it to work (calling CryptAcquireContext,
CryptGenRandom and CryptReleaseContext in that order). A sample is given on
the Microsoft page.

HTH,
Wolfgang

"CLEAVEAGE" <iamcl...@shaw.ca> schrieb im Newsbeitrag
news:23FTa.496104$3C2.13...@news3.calgary.shaw.ca...

0 new messages