www.delorie.com/djgpp/v2faq/faq193.html | search |
| Previous | Next | Up | Top |
Q: I keep getting the same random numbers each time I run my program. How do I get a different series on every run?
rand
and random
. The former is part of the ANSI C Standard, and is therefore very portable to other
environments. The latter is available on almost every Unix platform, but is generally unsupported by DOS/Windows compilers. On the other hand, series produced by random
have better
qualities than those produced by rand
. In particular, the least-significant bits in the numbers produced by random
are much more random than those you get from
rand
, so if you need, say, a random number between 0 and 4, and portability is not an issue, you will get better results with random () % 5
. However, the DJGPP
implementation of rand
is quite good, so when portability is important, you should use rand
.
Both rand
and random
return a pseudo-random integer in the range [0..RAND_MAX]
, where RAND_MAX
is defined in the stdlib.h header.
By default, every time you restart a program, you get the same series of pseudo-random numbers. This is important in some applications, because it allows to reproduce exactly the results of running
a program which used random series, and thus makes debugging easier. But sometimes, e.g. in a game, you will want a different series every time. To achieve that, you need to initialize the random
series with a different seed. Two functions provided for this purpose, srand
and srandom
, will seed the series generated, respectively, by rand
and
random
. You seed the series with a single call to srand
or srandom
, and then proceed by calling rand
or random
as usual.
A popular way of getting a different seed every run is to use the current system clock as the seed, like this:
srand (time (NULL));If the 1-second granularity of the values returned by
time
is not enough for you (e.g., if you need to generate more than one series every second), use gettimeofday
or
uclock
, or use the values returned by rand
as an argument to srandom
(or vice versa).
webmaster donations bookstore | delorie software privacy |
Copyright ⌐ 1998 by Eli Zaretskii | Updated Sep 1998 |
You can help support this site by visiting the advertisers that sponsor it! (only once each, though)