February 3rd, 2004, 08:19 PM
random numbers question
i got a questoin about the next code:
rndNum = rand ()%6;
could somone explain how it worke.s..cuz as i see it it jsut calls 2 function 2 times..why can' we call jsut one..and what will be the diffrentces????
thx in advance
February 3rd, 2004, 08:58 PM
All random numbers generated by computer, require to use some sort of formula. Thus, the generated numbers are pseudorandom and follow a specific sequence if we always starts from the same point. In order to further randomize the number, we should change the starting point whenever the program start.
In your example, srand(clock()) should only be called once. This function uses the processor time retrieved from clock() to set the random starting point, also known as random seed. As for the second function call, rand(), it generates the random number.
Hope this helps.
February 4th, 2004, 06:46 AM
Here's something simple which is consistent with the response from Kheun. Take a look...
static const int random(void)
static bool is_init = false;
is_init = true;
You're gonna go blind staring into that box all day.
February 4th, 2004, 02:53 PM
I don't know how good of a random number generator you need, but rand() is not a good choice for *serious* random number generation. If you need something more robust, do a search for "Mersenne Twister".
February 4th, 2004, 05:49 PM
rand() is compiler implementation specific. I guess rand() will give quite good chi-square test result (but again, it depends on the compiler vendor), at least for normal use of pseudo-random numbers.
The seed for the pseudo-random algorithm (which you initialize with srand()) can be very important--again, depending on what your application is using the pseudo-random numbers for. You don't want to use clock() for srand(), because it will most likley return the same value all times (if called once from the same location in your code). This is due to that clock() represents the life-time of the process, ie the tme your process has lived. Try this little program and you'll see what I mean:
With my compiler (vc7) it prints out zero each run... Really bad choice for a seed.
/* tryclock.c */
Hope it helps,
PS,. For cryptography, rand() is no good. The same goes for using a (any) time function value as seed.
February 4th, 2004, 06:59 PM
Personally, I attempt to use the lowest significant bits from several time variables and mix them up to produce a good seed. (time(), QueryPerformanceCounter() or RDTSC, and/or other timers that exist on particular hardware on my system). It's a heck of a lot better than using just one time value, and it suits my needs -- though I admitt this may not be the best seed. Another possibility is to get seeds from www.random.org if your application is connected to the web.
Click Here to Expand Forum to Full Width