For example, the following expression:
r = (rand() % 10)+1;
Generates a random number from 1-10
.
How can we make it generate random numbers from 0-10
?
Thanks.
For example, the following expression:
r = (rand() % 10)+1;
Generates a random number from 1-10
.
How can we make it generate random numbers from 0-10
?
Thanks.
You're almost there! The
rand()
function returns a random value in a pretty large range (0 toRAND_MAX
). The use of the modulus operator wraps this down into a smaller range (from 0 to 9, since you're modding by 10) and then the +1 moves this to be from 1 to 10.To get values between 0 and 10, you can take
rand
and mod its value by 11:More generally, to get random values in the range [0, n], you can write
And finally, to get values in the range [k, n + k], you can write
Of course, as purists will point out, this isn't necessarily going to give you truly uniform values because modding
rand()
by some value will not distribute all the integers evenly. This usually isn't a problem (you'll be off by a very, very small amount), but if it is you may want to consider looking into a more robust random number generator thanrand()
.This is a basic way to generate random numbers. The line of code that uses static_cast seeds the random number generator based on the current time, which means you get more numbers besides between 0 and 10 instead of just one.
Here is simpler way of generating random numbers with modern C++.
You leave out the +1 to start with 0. And since there are 11 different values you want, you need to calculate the remainder modulo 11 instead of 10.
Note that you need to seed a PRNG so it doesn't always produce the same sequence.
And the standard
rand()
function sucks. The quality of random numbers is very low, and not fit for many purposes. I strongly recommend using a better generator.A Mersenne twister is a popular choice, and in one my projects I used Well512 since it's fast, good and easy to implement.
If the user must not predict the random numbers even those good PRNGs are not enough and you have to choose a cryptographic PRNG. They can neither be predicted (with realistic computational power) nor be distinguished from real random numbers unless you know the seed. They are a bit slower though.
Generating a uniform distribution is much simpler and less error prone in C++11 using std::uniform_real_distribution or for the integer case std::uniform_int_distribution. Here is a sample using std::uniform_real_distribution which displays a simple graphic to give a rough demonstration that it is uniform:
Sample result:
Some of the sample code was taken from this reference.