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
da = np.diff(times)
if da.sum < 1: break
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) np.sort(x) 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.