# Generating Random Numbers

To be precise, random number generation functions, including rand, return pseudo-random numbers as opposed to truly random numbers, so whenever I say random, I actually mean pseudo-random. Before using the rand function you need to seed (i.e., initialize) the random number generator with a call to srand. This assures that subsequent calls to rand won’t produce the same sequence of numbers each time the program is run. The simplest way to seed the random number generator is to pass the result from a call to clock from the header as an unsigned int. Reseeding a random number generator causes number generation to be less random.

The rand function is limited in many ways. To begin with, it only generates integers, and only does so using a uniform distribution. Furthermore, the specific random number generation algorithm used is implementation specific and, thus, random number sequences are not reproducible from system to system given the same seed. This is a problem for certain kinds of applications, as well as when testing and debugging.

If you want to generate some random floating-point numbers in the interval of [0.0, 1.0) with a uniform distribution. The C++ standard provides the C runtime function rand in the header that returns a random number in the range of 0 to RAND_MAX inclusive. The RAND_MAX macro represents the highest value returnable by the rand function. A demonstration of

using rand to generate random floating-point numbers below.

#include <cstdlib> #include <ctime> #include <iostream> using namespace std; double doubleRand( ) { return double(rand( )) / (double(RAND_MAX) + 1.0); } int main( ) { srand(static_cast(clock( ))); cout << "expect 5 numbers within the interval [0.0, 1.0)" << endl; for (int i=0; i < 5; i++) { cout << doubleRand( ) << "\n"; } cout << endl; }

The program above should produce output similar to:

expect 5 numbers within the interval [0.0, 1.0)

0.010437

0.740997

0.34906

0.369293

0.544373

A much more sophisticated alternative to rand is the Boost Random library by Jens Maurer. The Boost Random library provides several high-quality random number generation functions for both integer and floating-point types, and support for numerous kinds

of distributions. Below code demonstrates how you can produce random floating- point numbers in the interval [0,1).

#include <boost/random.hpp> #include <iostream> #include <cstdlib> using namespace std; using namespace boost; typedef boost::mt19937 BaseGenerator; typedef boost::uniform_real Distribution; typedef boost::variate_generator<basegenerator, distribution=""> Generator; double boostDoubleRand( ) { static BaseGenerator base; static Distribution dist; static Generator rng(base, dist); return rng( ); } int main( ) { cout << "expect 5 numbers within the interval [0,1)" << endl; for (int i=0; i < 5; i++) { cout << boostDoubleRand( ) << "\n"; } cout << endl; }

The main advantage of the Boost Random library, is that the pseudo-random number generation algorithm has guaranteed and reproducible randomness properties based on the precise algorithm chosen. In above code I use the Mersenne Twister generator (mt19937) because it offers a good blend of performance and randomness.

###### Related articles

- C++ – Fisher-Yates Shuffle (bradenlenz.com)
- C++ – Rock Paper Scissors Game (bradenlenz.com)
- Write Random Numbers to a File and Read Into Vector in C++ (grahamscode.wordpress.com)
- How to Generate Random Numbers in Java between Range – Example Tutorial (javarevisited.blogspot.com)
- Representing Large Fixed-Width Integers in C++ (alikhuram.wordpress.com)
- random number generator error c++ MFC (stackoverflow.com)
- Random Numbers in C (coffeetoma.wordpress.com)
- Generating two independentely seeded random number lists in c (stackoverflow.com)

Posted on May 20, 2013, in Algorithms, C++ and tagged Algorithm, Floating point, Input/output, Integers, Iostream, Mersenne Twister, Pseudorandom Numbers, rand function, random floating-point numbers, Random number generation, reproducible randomness, srand, truly random numbers. Bookmark the permalink. 4 Comments.

Nice explanation 😉

Great one…..

It depends how many random numbers you want. If you want a million every second, for some statistical or simulation process or (as in something I’m working on) a graphics program, then you need a deterministic process which reliably gives a stream of pseudo-random numbers.

On the other hand, what if you want only 100 bits? Maybe you want to construct a password and you want 100 “random” bits from somewhere: I have experimented with using the human element. I make a bit generator which is fairly simple but runs rapidly, so the computer says “press A” and while I’m hunting for the A key on the keyboard, the bit generator is generating a few thousand pseudo-random bits. The point is that it’s the human random timing which determines which bit (in the sequence) is used. When I press the A key, the bit generator pauses and the most recent bit (or series of a few bits) is used. The computer then asks for a different key and the bit generator continues from where it left off.

This is repeated many times, for various keys which the computer asks, which I can’t predict. All you need is a moderately random way of inventing which key to ask for, and the human timing uncertainties will do all the rest. When I see “X” on the screen, quite a lot of brain processes are called upon: vision, recognition, memory of where that key is on the keyboard, instructions to muscles, control to get the finger on the key. That takes half a second (if you’re lucky and a good typist) to many seconds (if you’re a bad typist or you get distracted, or need to sneeze, etc.)

That means the _timing_ (between the computer’s request for a letter and my actually pressing the key) is unrepeatable. The human body, at the micro level, wobbles and vibrates, so timing is highly variable at the millisecond to tenth of a second level. An extra hundredth of a second in pressing the key means the bit generator has gone on a few hundred more bits.

I’ve used this successfully to construct passwords. I tell my program I want a password of (for example) 12 characters, including 4 capital letters, 4 digits and 4 small letters. The computer then works out that this needs, say, 60 bits, so asks me to press various keys, and the timing of those yields a few bits each. After maybe 20 keypresses, the computer has enough bits and contructs the password.

I recommend this as a source of a small number of bits. The program is simple and it is quick to run.

very nice idea indeed. I appreciate it.