www.delorie.com/djgpp/v2faq/faq193.html   search  

| Previous | Next | Up | Top |

22.22 How to produce random numbers?

Q: How do I produce random numbers with DJGPP?

Q: I keep getting the same random numbers each time I run my program. How do I get a different series on every run?


A: DJGPP has in its library two functions to produce series of pseudo-random(Note: Since these series are computed using a deterministic algorithm, they are not really random. Real random numbers can only be a result of unpredictable physical processes such as radioactive decay etc. However, a good algorithm for pseudo-random numbers produces a series of numbers that pass many tests for randomality.) numbers: 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  

Powered by Apache!

You can help support this site by visiting the advertisers that sponsor it! (only once each, though)