I want to seed R's internal unif_rand()
in a multithreaded environment. The code below generates a 2-column matrix of uniform random numbers within 2 threads. The results are interesting.
struct mtRunif: public RcppParallel::Worker
{
int Nrow; // number of rows in matrix.
double *v; // point to the 0th element of the 0th column.
void operator() (std::size_t st, std::size_t end)
{
// st = 0 in the 0th thread, 1 in the 1st thread.
double *vst = v + st * Nrow;
for(int i = 0; i < Nrow; ++i)
{
vst[i] = unif_rand();
}
}
mtRunif(int Nrow, double *v): Nrow(Nrow), v(v)
{
RcppParallel::parallelFor(0, 2, *this);
}
};
// [[Rcpp::export]]
NumericMatrix testSeeding(int sampleSize)
{
NumericMatrix rst(sampleSize, 2);
mtRunif(sampleSize, &*rst.begin());
return rst;
}
/***R
N = 100
set.seed(42); tmp = testSeeding(N)
set.seed(42); tmp2 = testSeeding(N)
# see if sequences are identical
range(tmp[, 1] - tmp2[, 1]); range(tmp[, 2] - tmp2[, 2])
# [1] 0 0
# [1] 0 0
N = 1000
set.seed(42); tmp = testSeeding(N)
set.seed(42); tmp2 = testSeeding(N)
range(tmp[, 1] - tmp2[, 1]); range(tmp[, 2] - tmp2[, 2])
# [1] -0.9655154 0.8989870
# [1] -0.969356 0.963239
*/
The results suggest set.seed()
controls the randomness in all threads for small sample sizes? Initially I expected set.seed()
would be effective in no more than 1 thread. I do not want to exploit the conclusion because it could be absolutely wrong. On the other hand, is there a seeding function for unif_rand()
akin to std::srand()
for std::rand()
?
Thank you!