Spica Spica - 8 months ago 32
Python Question

Constraining random number generation in Python

I am trying to create a loop in Python with numpy that will give me a variable "times" with 5 numbers generated randomly between 0 and 20. However, I want there to be one condition: that none of the differences between two adjacent elements in that list are less than 1. What is the best way to achieve this? I tried with the last two lines of code, but this is most likely wrong.

for j in range(1,6):

times = np.random.rand(1, 5) * 20
print times

da = np.diff(times)

if da.sum < 1: break

For instance, for one iteration, this would not be good:

4.25230915 4.36463992 10.35915732 12.39446368 18.46893283

But something like this would be perfect:

1.47166904 6.85610453 10.81431629 12.10176092 15.53569052


Since you are using numpy, you might as well use the built-in functions for uniform random numbers.

def uniform_min_range(a, b, n, min_dist):
    while True:
        x = np.random.uniform(a, b, size=n)
        if np.all(np.diff(x) >= min_dist):
            return x

It uses the same trial-and-error approach as the previous answer, so depending on the parameters the time to find a solution can be large.