Generate pseudo random numbers in C++

Generating random numbers is very useful especially in simulations of games, scientific simulations, computer security, statistics modeling programs, etc. But computers produce predictable results and hence they can’t be totally random but can only simulate randomness. Pseudo-random number generators are most often used for this.

So here in this tutorial, I will tell you how we can generate pseudo random numbers in C++ with example. So continue through this article.

Pseudo-Random Number Generators (PRNGs)

A PRNG is an algorithm that uses mathematical formulas to produce a series of random integers. It takes a seed integer value and performs some mathematical operations on it. After using the algorithm of mathematical operations, the seed value is transformed into a number that seems totally unrelated to the seed. Now, this number is taken and the same algorithm is applied to produce the next number. This number also appears to be totally unrelated to the number it is generated from. By continually applying this algorithm to the last generated number, a series of random numbers can be generated. The period of randomness depends on the complexity of the algorithm.

 

C++ comes with a built-in Pseudo-Random Number Generator in the header file <cstdlib.h> and is implemented using the following functions:

1. int rand(void) – Returns a random integer in the range 0 to RAND_MAX
where RAND_MAX is a constant whose value differs in different implementations (min. value is 32767)

2. void srand(unsigned seed) – Seeds the pseudo-random generator used by rand().
where the seed is an unsigned integer value considered as the “starting point” for generating random numbers.

 

rand()

A series of truly random numbers is when every number from 0 to RAND_MAX has an equal chance of being chosen each time rand() is called. In reality, this is not the case. See the following example in which we generate a series of random numbers with rand():

#include<cstdlib>
#include<iostream>
using namespace std;

int main(){

    for(int i=0; i<4; i++)
        cout<<rand()<<" ";

    return 0;
}   

Output on program run 1:

41 18467 6334 26500

Output on program run 2:

41 18467 6334 26500

 

Note:  If we want numbers to be generated in a given range, we can use the modulus operator(%). 

Say, for example, we want a series of 4 random numbers between 1 to 10. To do this, we modulus the number generated with 10 because any integer modulus 10 will produce a number from 0-9 (If we divide a number by 10, the remainder has to be from 0 to 9).

18467 % 10 = 7
6334 % 10 = 4

But we want numbers from 1 to 10, so we add 1 to each output.

#include<cstdlib>
#include<iostream>
using namespace std;

int main(){

    for(int i=0; i<4; i++)
        cout<<(rand()%10)+1<<" ";

    return 0;
}

Output on program run 1:

2 8 5 1

Output on program run 2:

2 8 5 1

The output shows that if we run the program many times, we end up with the same sequence of random numbers each time. This is because these numbers are not truly random, but pseudorandom.

 

srand()

To resolve the problem of the same generated series in rand(), srand() takes a seed value as input for rand() that changes the generated series of random values on every different seed. This process of “seeding” the random number sequence so we start at a different place is called Randomizing.

The most common practice is to use the current time as the seed. For this, time() function declared in <time.h> is used. Hence, the following program will generate a different series of numbers in every program run:

#include<cstdlib>
#include<iostream>
#include<time.h>
using namespace std;

int main(){

    srand(time(NULL)); 
    for(int i=0; i<4; i++)
        cout<<(rand()%10)+1<<" ";

    return 0;
}

Output on program run 1:

8 1 10 3

Output on program run 2:

7 8 2 3

Note:

  1.  If the seed value is the same at every program execution, the program will generate the same series at each run.
  2. Seed the program only once during program execution, at the beginning. Multiple calls to srand() makes the numbers less evenly distributed i.e. the results might be less random.

 

Further reading

The Standard Library (STL) in C++ provides two types of pseudo-random generators:

  1. Require a seed value
  2. Require an input value with each call and doesn’t require a seed value

Every PRNG outputs a different data type.

 

Conclusion

A good PRNG is one that generates a series of numbers similar enough to a truly random sequence of numbers in many statistical tests. All PRNGs are actually deterministic and their outputs are periodic, but the period is very huge.

Hence, all random number generators are actually pseudo-random generators. The numbers are distributed such that the output is a random sequence, but after enough time, the sequence starts repeating.

Also, read: Program to solve the knapsack problem in C++

 

Leave a Reply

Your email address will not be published.