Task:
- Generate a pair of random numbers
(i,j)(order doesn't matter:(i,j)is equivalent to(j,i)). - The pair must consist of two distinct values:
i != j - Pairs must be uniformly distributed. In other words, the probability is the same for all the possible pairs.
- Do this at a constant time.
1st attempt
Constant time? YES. Uniformly distributed? NO
x = np.random.randint(low=0, high=10 - 1)
y = np.random.randint(low=x + 1, high=10)
Visualizing the samples (by disregarding the order) :
Samples visualization (not uniformly distributed)
You can easily the effect of restricting the y to be larger than x, meaning higher pairs have higher probability (opacity here expresses density).
2nd attempt
Constant time? NO. Uniformly distributed? YES
x = np.random.randint(low=0, high=nbr_values)
y = np.random.randint(low=0, high=nbr_values)
while x == y:
y = np.random.randint(low=0, high=nbr_values)
Visualizing the samples:
Samples visualization (uniformly distributed)
PS: it's not a homework, I'm experimenting with stochastic optimization techniques that use random neighbor generation using a swap operation.
Aucun commentaire:
Enregistrer un commentaire