I am trying to generate 1000 numbers using exponential distribution with parameter 1.
After setting the seed value to 1, I tried both rexp(1000, 1) and replicate(1000, rexp(1, 1)), but the medians of the resulting two vectors are different.
I expected the vectors generated by the two expressions to be the same, because they were both sampled from the same exponential distribution under the same seed value.
What is the difference between rexp(1000, 1) and replicate(1000, rexp(1, 1))? Which should I use in practice?
Here is the code that I tried:
> options(digits = 2)
> set.seed(1)
>
> a <- rexp(1000, 1)
> b <- replicate(1000, rexp(1, 1))
>
> median(a)
[1] 0.73
> median(b)
[1] 0.68
The problem here is that the random seed changes after it is used, so your seed of 1 is different when you generate
b. You have to reset the seed before you createbif you want it to be the same asaAs for which you should use, it is definitely
rexp(1000, 1), because this generates a single call to the underlying C code as opposed to 1000 calls. Although we can see from above that the two codes generate the same results, a simple benchmark shows thatrexpis about 50 times faster.Created on 2023-02-27 with reprex v2.0.2