Skip to content
Prev 3620 / 10988 Next

[Rcpp-devel] R random numbers vs c++

On 22 March 2012 at 08:20, Davor Cubranic wrote:
| On 2012-03-22, at 5:41 AM, Glenn Lawyer wrote:
| 
| > Is there a reason to prefer Rcpp::runif over the c++ rand() for, say, accepting a state in a Markov chain simulation? Is one more random than another? faster?
| 
| I'd use the R random generator so your C++ code is in sync with R in terms of seeds and random sequences. For instance, if you're running your simulation in parallel on multiple machines or cores, you can use one of the RNG's designed specifically to avoid correlations between individual instances, such as SPRNG or RNGstream.

Ah, yes, indeed. Sorry I omitted that. It is indeed important that

    set.seed(42); rnorm(6)

and

    f <- cxxfunction(,body='RNGScope tmp; return rnorm(2)', plugin="Rcpp")
    set.seed(42); c(rnorm(2), f(), rnorm(2))

return the same result:

    R> f <- inline::cxxfunction(,body='RNGScope tmp; return rnorm(2);', plugin="Rcpp")
    R> set.seed(42); c(rnorm(2), f(), rnorm(2))
    [1]  1.370958 -0.564698  0.363128  0.632863  0.404268 -0.106125
    R> 
    R> set.seed(42); rnorm(6)
    [1]  1.370958 -0.564698  0.363128  0.632863  0.404268 -0.106125
    R> 

so that you can mix and match.

Dirk