samedi 29 juillet 2017

How to generate list of unique random floats in Python

I know that there are easy ways to generate lists of unique random integers (e.g. random.sample(range(1, 100), 10)).

I wonder, whether there is some better way of generating a list of unique random floats, apart from writing a function that acts like range, but accepts floats like this:

import random

def float_range(start, stop, step):
    vals = []
    i = 0
    current_val = start
    while current_val < stop:
        vals.append(current_val)
        i += 1
        current_val = start + i * step
    return vals

unique_floats = random.sample(float_range(0, 2, 0.2), 3)

There must be a better way.




Aucun commentaire:

Enregistrer un commentaire