Table of Contents
1. Introduction
Generating random numbers within a specific range is a common task in C++ programming. The requirement often involves creating random integers or floating-point numbers within a range, like 1 to 10. This article will explore various methods to generate random numbers in this range, including integers within the range, excluding the boundaries, and decimal values.
2. Using rand() Function with Modulus Operator
C++ programming language comes with an in-built pseudo-random number generator (PRNG)
along with rand ()
and srand ()
functions which can be used to generate random numbers.
The rand()
function, found in the <cstdlib>
header, generates a random number. Using the modulus operator (%
), we can confine this number to a specific range.
2.1 Generate random numbers between 1 and 10, including 1 to 10
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(time(0)); // Initialize random number generator. cout<<"Random numbers generated between 1 and 10:"<<endl; for(int i=0;i<10;i++) cout << (rand() % 10) + 1<<" "; return 0; } |
1 2 3 4 |
Random numbers generated between 1 and 10: 3 9 5 4 8 9 3 5 10 10 |
When we invoke srand(time(0))
, we’re essentially telling the random number generator to start with a seed based on the current time. This means that each time we run our program, time(0)
will likely return a different value, leading to a different starting point for the random number sequence. As a result, the sequence of numbers generated by rand() will be different in each run.
rand()
function generates random number and rand()%10
returns last digit of the number. Since we require random number between 1 and 10, we have used rand()%10+1
to generate random number between 1 and 10 in C++.
Let’s understand srand()
and rand()
functions a little bit in detail.
Srand()
: This function takes the initial value which is used by rand()
to create random numbers. It’s called only once, to initiate the process of random number.
Rand()
: This function is used to generate random numbers. It is called several times until we want to generate random numbers. Provides a sequence of random numbers every time it is called.
2.2 Generate random numbers between 1 and 10, excluding 1 and 10
Following is the program used to generate random numbers between 1 to 10, excludes 1 and 10.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(time(0)); // Initialize random number generator. cout<<"Random numbers generated between 1 and 10:"<<endl; for(int i=0;i<10;i++) cout << 1+(rand() % 8) + 1<<" "; return 0; } |
Output:
1 2 3 4 |
Random numbers generated between 1 and 10, excluding 1 and 10: 6 6 5 6 4 9 7 7 5 5 |
2.3 Generate random numbers between 1 and 10 including decimal values
Following is the program used to Random numbers generated between 1 to 10 including decimal values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include<iostream> #include<ctime> #include<cstdlib> using namespace std; int main() { cout<<"Random numbers generated between 1 to 10 including decimal values:"<<endl; double u; srand( unsigned(time(0))); for(int i = 0;i< 10 ; i++) { u=(double)rand()/(RAND_MAX)+1 +(rand()%9); cout<<"\t"<<u; } return 0; } |
Output:
1 2 3 4 |
Random numbers generated between 1 to 10 including decimal values: 1.98767 2.5695 9.31038 8.05644 1.14007 1.55395 9.24143 6.92331 4.13387 8.3827 |
3, Using C++11 <random> Library
C++11
introduced a more robust random library in <random>
. It provides a more uniform and reliable distribution of random numbers than rand()
function. It allows more control and produces a better distribution of random numbers.
3.1 Generate random numbers between 1 and 10, including 1 and 10
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <random> #include <iostream> int main() { std::random_device rd; std::mt19937 eng(rd()); std::uniform_int_distribution<> distr(1, 10); int randomNumber = distr(eng); std::cout << "Random Number: " << randomNumber << std::endl; return 0; } |
1 2 3 |
Random Number: 6 |
Let’s understand more about code in 3 sections.
-
Initializing the Random Number Generator:
std::random_device rd
: Creates an instance of std::random_device. This object provides a source of non-deterministic random numbers (often based on hardware entropy sources), which we use to seed our random number generator.std::mt19937 eng(rd())
: Creates a Mersenne Twister random number generator engine (std::mt19937) seeded with the random value generated by rd. The Mersenne Twister is a popular choice for generating pseudo-random numbers due to its high quality and fast performance.
-
Setting Up the Distribution:
std::uniform_int_distribution
<> distr(1, 10);: Constructs a uniform integer distribution object. This distribution produces integers in therange [1, 10]
, meaning it includes both 1 and 10. The distribution ensures that each integer in this range has an equal probability of being chosen.
-
Generating the Random Number:
int randomNumber = distr(eng)
: Generates a random integer. The distr object uses the Mersenne Twister engine eng to produce a random number that fits the uniform distribution we defined (between 1 and 10, inclusive).
3.2 Generate random numbers between 1 and 10, excluding 1 and 10
Change following line the above code:
1 2 3 |
std::uniform_int_distribution<> distr(1, 10); |
to
1 2 3 |
std::uniform_int_distribution<> distr(2, 9); |
3.3 Generate random numbers between 1 to 10 including decimal values
Generate random numbers between 1 to 10 including decimal values, we need to use uniform_real_distribution
rather than uniform_int_distribution
. Everthing else remain same.
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <random> #include <iostream> int main() { std::random_device rd; std::mt19937 eng(rd()); std::uniform_real_distribution<> distr(1, 10); double randomNumber = distr(eng); std::cout << "Random Decimal Number: " << randomNumber << std::endl; return 0; } |
4. Performance Comparison
Using rand() Function: This method is generally faster due to its simplicity but at the cost of potentially less uniform distribution and randomness quality.
Using C++11 <random> Library: While this might be marginally slower due to its more complex nature, it provides a significantly better distribution and quality of randomness, making it the preferred choice for applications where randomness quality is important.
5. Conclusion
Choosing the right method for generating a random number between 1 and 10 in C++ depends on the specific requirements of our application. If we’re working on simple, small-scale projects or where high-quality randomness isn’t crucial, using the rand()
function is sufficient and straightforward. However, for more serious applications, especially those requiring more reliable and uniform random number generation, the C++11 <random> library is a superior choice. It offers not only better randomness but also more options to tailor the random number generation process to your specific needs.