Generating independent random variables

Viewed 397

I would like to generate n independent uniform variables on [0,1]. I am not sure if numpy.random.uniform(0,1,size=n) is fine because nothing tells me that the data is independently generated.

Do I have instead to loop n times on numpy.random.uniform(0,1,size=1)? Do I have to do something with the seed?

2 Answers

You can use the function exactly as you wrote: numpy.random.uniform(0,1,size=n). Do not loop.

From the documentation "... any value within the given interval is equally likely to be drawn by uniform." Each value is as independent as a computer can make them.

Setting a seed will create the same array of random numbers each time. This is useful for testing so you can get the same output each time, but if you want the array to be a new set of random numbers each time the function is called, don't set a seed.

numpy.random.uniform(0,1,size=n) generates values as independently as possible using an pseudo-random number generator.

If you're not convinced, you can check that using the size argument and a for loop will give you exactly the same results:

import numpy as np

n = 5

np.random.seed(5)
print(np.random.uniform(0,1,size=n))

np.random.seed(5)
for _ in range(n):
    print(np.random.uniform(0,1))
Related