1
Random Numbers
•
In many applications, want to be able to generate
random numbers, permutations, etc.
Since computers are deterministic,
true
randomness
does not exist
Settle for pseudo-randomness
: sequence of numbers
that
looks
random, but is deterministically generated
Most random number generators use a “linear
congruential generator” (LCG):
o
Start with a seed number X
0
o
Next “random” number given by: X
n+1
= (
a
X
n
+
c
) mod
m
o
Effectiveness is
very
sensitive to choice of
a
,
c
, and
m
o
Note: the sequence of random numbers must eventually cycle
The
rand()
Function
•
In C/C++, there exists a function for generating
pseudo-random numbers:
int rand(void)
Part of
<stdlib.h>
library
Returns integer between 0 and
RAND_MAX
, inclusive
o
Values supposed to be “uniformly” distributed in range
o
RAND_MAX
guaranteed to be at least 32767 (often larger)
In most implementations, uses LCG
Seeded using:
void srand(unsigned int seed)
o
Often set to current system time:
srand(time(NULL));
For our purposes, we accept approximation:
(rand()/((double)RAND_MAX + 1))
~ Uni[0, 1)
Shuffling Deck of Cards
•
Want to generate a random permutation of set
E.g., completely shuffle a deck of cards
Want all permutations to be equally likely
void shuffle(int arr[], int n) {
for(int i = n - 1; i > 0; i--) {
double u = uniformRand(0, 1);
// u in [0, 1)
// pick one of "remaining" i positions
int pos = (int)((i + 1) * u);
swap(arr[i], arr[pos]);
}
}
Bad, But Common, Shuffle
•
Common mistake in creating random permutation
void badShuffle(int arr[], int n) {
for(int i = 0; i < n; i++) {
double u = uniformRand(0, 1);
// u in [0, 1)
// pick any position
int pos = (int)(n * u);
swap(arr[i], arr[pos]);
}
}
Has n
n
execution paths, but only n! permutations