user2300944
user2300944

Reputation: 77

Why do R commands rnorm() and qnorm(runif()) generate different random numbers?

I set the seed, generate uniformly distributed random numbers, and use the inverse CDF method to get a set of normally distributed random numbers. Then, I reset the seed and generate normally distributed random numbers using rnorm(). The results are different. Does not the random number generator in R default to the Mersenne-Twister algorithm to generate integers? Should not all the other random numbers in R (normal, uniform, exponential, etc. distributions) be some deterministic transformation of these pseudo-random integers?

set.seed(1)
u1 <- runif(5)
u1
# [1] 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819
z1 <- qnorm(u1)
z1
# [1] -0.6264538 -0.3262334  0.1836433  1.3297993 -0.8356286
set.seed(1)
z2 <- rnorm(5)
z2
# [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078

And yes, I see that some elements match, but do not necessarily appear in the same order. Can someone please explain?

Upvotes: 4

Views: 1280

Answers (1)

Thilo
Thilo

Reputation: 262684

It does look like the elements all appear and in the same order, but there is always an extra element interspersed in the output of your first method.

That seems to suggest that rnorm consumes two random numbers for each iteration, and that is in line with this answer.

case INVERSION:
#define BIG 134217728 /* 2^27 */
/* unif_rand() alone is not of high enough precision */
u1 = unif_rand();
u1 = (int)(BIG*u1) + unif_rand();
return qnorm5(u1/BIG, 0.0, 1.0, 1, 0);

Looks like it takes the second number for the less significant bits.

That would mean that the "same" numbers you observed also become slightly different when you look at more digits.

Upvotes: 2

Related Questions