I am having trouble using replicate()
function in R to generate random numbers with Rcpp function. Consider the following function in R:
trial <- function(){rnorm(1)}
replicate(10, trial())
It generate 10 random numbers from Gaussian distribution. It works completely fine and produces result like this:
[1] 0.7609912 -0.2949613 1.8684363 -0.3358377 -1.6043926 0.2706250 0.5528813 1.0228125 -0.2419092 -1.4761937
However, I have a c++ function getRan()
that generate a random number from Gaussian distribution. I again used replicate to call the function like this:
replicate(10,getRan())
It creates a vector of same number like this:
> replicate(10,getRan())
[1] -1.374932 -1.374932 -1.374932 -1.374932 -1.374932 -1.374932 -1.374932 -1.374932 -1.374932 -1.374932
> replicate(10,getRan())
[1] -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785 -0.3273785
> replicate(10,getRan())
[1] -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953 -0.7591953
> replicate(10,getRan())
[1] -1.698935 -1.698935 -1.698935 -1.698935 -1.698935 -1.698935 -1.698935 -1.698935 -1.698935 -1.698935
However, if i call the function multiple times, it works fine:
getRan()
[1] 1.345227
> getRan()
[1] 0.3555393
> getRan()
[1] 1.587241
> getRan()
[1] 0.5313518
So what is the problem here? Does the replicate()
function repeat the same function return from getRan()
instead of calling getRan()
multiple times? Is it a bug?
PS: I know I can use rnorm(n)
to generate n normal random number, however, I want to use the c++ function to do more complex calculations based on generating random numbers
PPS: this is my c++ code:
double getRan(){
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::normal_distribution<double> distribution (0.0,1.0);
double epi = distribution(generator);
return epi;
}