0

The following algorithm is designed to generate random list of integers with a minimum distance. More details are here: Python: Random list of numbers in a range keeping with a minimum distance

I want to know how is it possible to modify so that it works for floats instead, I did some attempts but I get some exceptions where the minimum distance is not obeyed (just by a fraction but it's enough to mess my algorithm).

def ranks(sample):
"""
Return the ranks of each element in an integer sample.
"""
indices = sorted(range(len(sample)), key=lambda i: sample[i])
return sorted(indices, key=lambda i: indices[i])


def sample_with_minimum_distance(n, k, d):
    """
    Sample of k elements from range(n), with a minimum distance d.
    """
    sample = random.sample(sorted(np.linspace(n - (k - 1) * (d - 1), 0)), k)
    return [s + (d - 1) * r for s, r in zip(sample, ranks(sample))]
  • 2
    Are you sure the lack of distance isn't due to the limited precision of floats? For which n, k, d do you have problems? – MisterMiyagi Sep 24 '21 at 16:50
  • Why not just add some cushion to your target minimum distance? – John Coleman Sep 24 '21 at 17:36
  • 1
    If you want perfect precision you'd have to use the `decimal` module. See: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Random Davis Sep 24 '21 at 17:37
  • This algorithm was designed for integers only that's why you see values like (k-1) and (d-1), I did some changes but nothing worked from me.. and the difference is not really a small fraction it is sometimes of the order of 0.1 (It's ok if it affects the results after 4 decimal numbers)... Can you suggest a corrected version? I might not understand what you intend to say. Thx – Firas Bejar Sep 27 '21 at 07:33

0 Answers0