A true random number generator has three important properties:
Very rarely is a random number generator all of: “good”, “cryptographically strong”, and “true”. This isn't necessarily a bad thing, but it's worth remembering when evaluating claims that one random number generator is “better” than another.
<stdlib.h>
provides us with two random number generator functions:
rand()
srand()
rand()
RAND_MAX
.
RAND_MAX
is a symbolic constant, defined in <stdlib.h>
RAND_MAX
has an equal chance
of being chosen each time rand()
is called. int number = rand(); printf("%d\n", number);
1804289383
Why is the number so big? Shouldn’t we randomly get a small number every once in a while?
srand()
srand()
with a different seed
every time it is called.
rand()
to get random numbers.
time(NULL)
returns the number of seconds since the start of 1970.
srand(time(NULL)); printf("%d\n", rand());
1501268540
rand()
and srand()
to produce values in a particular range,
we may generalize: int number = a + rand() % b;
a
is the shifting value (the first number in the desired range
of consecutive integers)
b
is the scaling factor (the width of the desired range of
consecutive integers).
b
different numbers, starting at a
.
srand(time(NULL)); for (int row = 0; row < 7; row++) { for (int i = 0; i < 20; i++) printf(" %d", 18 + rand() % 8); printf("\n"); }
22 21 24 23 18 25 20 24 20 18 25 20 21 18 21 25 23 22 23 24 24 19 24 25 21 19 20 24 20 25 25 25 21 23 22 21 23 25 19 25 25 18 19 21 19 23 20 24 19 25 22 25 18 20 24 21 21 19 20 24 18 19 23 21 25 19 24 22 18 18 21 18 18 23 21 19 20 23 25 21 22 22 20 22 24 19 25 20 20 19 18 20 21 23 24 20 24 22 24 25 22 19 25 23 24 20 24 18 25 24 21 21 20 24 25 18 25 24 20 19 18 20 21 21 25 19 23 24 24 21 23 20 22 22 25 21 24 24 21 23