Skip to content

[R-pkg-devel] Managing RNG in C code

1 message · Charles Geyer

#
The answer is do not try to manage the RNG from C.  Just do

GetRNGstate();

then generate a lot of random variates and then

PutRNGstate();

just before leaving.  There is only one call to each in one call of C from
R.

This is TRT (the Right Thing).  Anything else is TWT (the Wrong Thing).

Starting an RNG a whole bunch of times with lots of different seeds doesn't
do random number generation.  You want one continuous stream.  Only then
does the RNG have the properties claimed for it.

Moreover, you want your code to follow the R way (the tao of R).  Your use
of RNG should be just like every other R function.

The user should be able to save .Random.seed and restore it and get the
same results with another run.  So the user is doing reproducible
research.  The user shouild be able to use RNGkind to change the random
number generator.  If you muck about with this you get in the way of the
users.  Your code is less useful not more.

In my packages that use random number generation (especially mcmc), this is
the policy I follow.  The only thing I do with the random number generator
is save .Random.seed before going from R to C and store the saved value in
the returned object so the user does not have to.

As with many problems, the right answer is don't do that!


Message: 1