3

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.

0

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.