Generating multiple pairs of unequal random integers in python/numpy

Viewed 418

In the context of a Monte Carlo simulation I am generating pairs of random indices, using

ij = np.random.randint(0, N, (n,2))

where n can be quite large (e.g. 10**6). I then loop over these pairs.

Issue:
I would like the numbers in each pair to be different.

The solutions that I found (e.g., using random.sample or np.random.choice) suggest generating number pair by pair. In my case it means calling the random numbers generator repeatedly in a loop, which slows down the code.

2 Answers

This is a simple way to do it:

import numpy as np

N = 10
n = 10000

np.random.seed(0)
i = np.random.choice(N, n)
j = np.random.choice(N - 1, n)
j[j >= i] += 1
print(np.any(i == j))
# False
ij = np.stack([i, j], axis=1)

One approach could be to iteratively update those elements that have the same pairs:

m = np.full(ij.shape[0], True)
while m.any():
    ij[m] = np.random.randint(0, N, (m.sum(),2))
    m = ij[:,0] == ij[:,1]
Related