lundi 29 juin 2020

Multiple sqeuences of random numbers without replacement

In numpy, I can use the code

from numpy.random import default_rng
rng = default_rng()
M, N, n = 10000, 1000, 3
rng.choice(np.arange(0, N), size=n, replace=False)

To get three random samples from 0 to 9 without replacement.

I would like to get thousands of such random sequences. What is the correct way to do this? I know I can do

np.array([rng.choice(np.arange(0, N), size=(n,), replace=False) for i in range(0, M)])

but I am wondering if there's a more efficient way to do this using numpy.

In this answer, the following way is recommended

np.argsort(rng.random((M,N)),axis=1)[:, :n]

which is superfast and elegant. However, the cost scales like N x M instead of n x M which I am hoping to achieve.

Are there any other methods out there?




Aucun commentaire:

Enregistrer un commentaire