Channels ▼

Open Source

C Snippet #10

Q: HOW DO I... create a unique series of random numbers?

A: Have you ever written some really killer C program -- such as a game -- that uses the rand() random number function, only to find that it seemingly isn't random after all? The problem isn't in rand() per se, but in the fact that it needs to be reseeded before use. What to seed it with? Why, a random number of course!

If you find this circular logic confusing, don't worry. The standard C library has just the function you need to provide a suitable seed for initializing the rand() function every time you start your program. Simply call the time() function and use it as the seed value! Simply by adding the one following line to your program, your random numbers will become truly random once again.

srand(((unsigned int)time(NULL)) | 1);

This is pretty straightforward, but you may be asking why OR the time with 1? The rand() and srand() functions are used to, respectively, access and seed a pseudo random number generator (RNG). Since the RNG is based on an algorithm, it's obviously not truly random (that's why it's called a pseudo-RNG). If you keep supplying it with the same seed using the srand() function, you'll get the same sequence of numbers when you call the rand() function. Nowadays, most RNGs in most compiler libraries are pretty good, but this wasn't always so and still isn't guaranteed. As it turns out, the randomness of an RNGs output may be influenced by whether the seed is odd or even. Since odd seeds are generally better in such instances, OR'ing the output with 1 may cut the available range of seed values in half, but it does help assure better quality results.

All that having been said, feel free to experiment with it. It may well be that your compiler's RNG is good enough not to need it. For more information, see section 7.20.2 in the ISO/IEC C standard (also referenced by the C++ standard).


--Bob Stout

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags


<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags


<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

