vendredi 24 septembre 2021

How can I modify the following algorithm so that it works on floats?

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.
    """
    i = round(random.uniform(0, 1), 2)
    sample = random.sample(sorted(np.linspace(n - (k - i) * (d - i), 0)), k) #generate a sample from the float list
    list_dist = [s + (d - i) * r for s, r in zip(sample, ranks(sample))]
    return(list_dist)



Aucun commentaire:

Enregistrer un commentaire