Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ random number generation

Tags:

c++

random

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.

like image 406
Simplicity Avatar asked Feb 07 '11 08:02

Simplicity


People also ask

Does C have a random number generator?

C library function - rand()The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.

How does random number generation work in C?

The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed. Although the generated numbers look unpredictable within one run of a program, the sequence of numbers is exactly the same from one run to the next.

How do you generate a random number between 1 and 10 in C?

In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.

What library is rand () in C?

1.1. The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.


1 Answers

You're almost there! The rand() function returns a random value in a pretty large range (0 to RAND_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:

r = rand() % 11;

More generally, to get random values in the range [0, n], you can write

r = rand() % (n + 1);

And finally, to get values in the range [k, n + k], you can write

r = rand() % (n + 1) + k;

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 than rand().

like image 126
templatetypedef Avatar answered Nov 02 '22 11:11

templatetypedef