# [R] random seed puzzle

drf5n@maplepark.com drf5n at maplepark.com
Tue Aug 3 23:54:04 CEST 2004

```> > On Mon, 2 Aug 2004 17:50:44 -0500, "Bickel, David"
> > <DAVID.BICKEL at PIONEER.COM> wrote:
> >
> > >After reading the help page on set.seed, I am unsure about
> > how to solve the following problem. I need to call function f
> > a thousand times. The list of values returned by f, should be
> > as random as possible. f calls g twice:
> > >	f <- function(){g1 <- g(1); g2 <- g(2); c(g1; g2)}
> > >The function g in turn calls sample and returns a number,
> > but also depends on its argument, so, starting from the same
> > seed, g(1) returns a different number than g(2). I need each
> > call to g to start with the same random number seed, so that
> > the values returned by f would not be affected by redefining
> > it this way:
> > >	f <- function(){g2 <- g(2); g1 <- g(1); c(g1; g2)}

You may need 2 or three independent streams of random numbers, and may
have to globally maintain their state variables.

rng.streams<-list()
set.seed(1); rng.streams[[1]]<-.Random.seed
set.seed(1964); rng.streams[[2]]<-.Random.seed
set.seed(1965); rng.streams[[3]]<-.Random.seed

g<-function(){print(sample(1:sample(1:10,1)))}

f<-function(){
x<-rnorm(1)  # use a system rn
rng.saved<-.Random.seed   # save system rng state
.Random.seed<<-rng.streams[[1]] #  F's stream
x[2]<-rnorm(1)
rng.streams[[1]]<<-.Random.seed
.Random.seed<<-rng.streams[[2]]  # 1st G stream
g()
rng.streams[[2]]<<-.Random.seed
.Random.seed<<-rng.streams[[3]]  # get 2nd g stream
g()
rng.streams[[3]]<<-.Random.seed  # save 2nd G stream

.Random.seed<<-rng.saved # restore system rng state
x
}

rng.streams<-list()
set.seed(1); rng.streams[[1]]<-.Random.seed
set.seed(1964); rng.streams[[2]]<-.Random.seed
set.seed(1965); rng.streams[[3]]<-.Random.seed
f()
f()
f()
set.seed(1964); rng.streams[[2]]<-.Random.seed
f()  # note that the 1st g() sample is reset

You could also save the rng state in f() before the first call to g(),
and restore it before the second call to g(), so the two calls use
effectively one g() worth of variates from a single system rng stream, but
depending on the g() internals, there could be unintended correlation
between the g() results.

good luck,
Dave
--
Dave Forrest
drf at vims.edu                                    (804)684-7900w
drf5n at maplepark.com                             (804)642-0662h
http://maplepark.com/~drf5n/

```