Having difficulty understanding random number generators and seeds?

posted Aug 31, 2012, 1:51 PM by Unknown user

In order to understand how setting the seed affects the random number generator output, you might want to try the following code in R

# set the seed and call the rng and notice that the output from the RNG is different each time you call the RNG
# sample(seq(1,10,1)) generates one (pseudo) random number between 1 and 10.
set.seed(199) # set the seed
sample(seq(1,10),1) # call the rng
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again

# notice that the following code reproduces the same random sequence
# output from the RNG because we used the same seed
set.seed(199) # reset the rng by setting with the same seed
sample(seq(1,10),1) # call the rng
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again

# Now try using a different seed
# and notice that the sequence of random numbers output from the RNG
# is different to the above.

set.seed(222) # reset the rng with a different seed
sample(seq(1,10),1) # call the rng
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again
sample(seq(1,10),1) # call the rng again

Comments