For Programmers: Free Programming Magazines  


Home > Archive > VC Language > June 2005 > rand function









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author rand function
stanley

2005-06-11, 3:59 pm

hi
i need to get a realy! randomal number in the range of 1-1000000
the problem is that i am using the time as the seed and because the end user
is a web site sometimes many users are using the system at the some time and
the rand result is not a unique number but the some one
what is the best way to get a pure randomal number in a situation like that
- many users at the some time using the some rand function?
thanks
stanley
here is my code:

srand( (unsigned)time( NULL ) );
int i=((rand() %1000000)+1;
Oleh Melnik

2005-06-11, 3:59 pm

> srand( (unsigned)time( NULL ) );
> int i=((rand() %1000000)+1;


Use srand once (for example, in app initialization).


Scott McPhillips [MVP]

2005-06-11, 3:59 pm

stanley wrote:
> hi
> i need to get a realy! randomal number in the range of 1-1000000
> the problem is that i am using the time as the seed and because the end user
> is a web site sometimes many users are using the system at the some time and
> the rand result is not a unique number but the some one
> what is the best way to get a pure randomal number in a situation like that
> - many users at the some time using the some rand function?
> thanks
> stanley
> here is my code:
>
> srand( (unsigned)time( NULL ) );
> int i=((rand() %1000000)+1;


Why do you seed the generator for every user? You should only seed it
when the program starts, then call rand each time you need a number.

The srand and rand functions are not a mathematically robust source of
random numbers. For "realy!" random numbers you will need to study the
extensive literature.

You could consider adding a little more randomness by incorporating the
current number of users, and/or by incorporating the
QueryPerformanceCounter() timer. For more mathematical rigor
investigate crypto key generation algorithms.

--
Scott McPhillips [VC++ MVP]

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com