I have already seen this question which explains how to get one random number between a float range and this which explains how I can get n different random numbers which are integers.

I want k unique random numbers which are float and also the range is float.

1 upvote
So, what have you tried? – Ulrich Eckhardt
The only method that I could think of is making a function which generates the first random float and then when I generate the second random float, I check if it is same as the first or not. Similarly for the third, I check it for first and second. Repeat until I get 4 different values – rjmessibarca
2 upvote
Well, add that and the code to your question. Then, detail why this solution isn't sufficient for you. To be honest, a question asking for code always has the smell of homework, and you can avoid that by showing your efforts. – Ulrich Eckhardt

3 Answers 11

up vote 2 down vote accepted

Method 1 :

import random

def get_rand_array(lower_bound, upper_bound, total_nums):
    rand_set = set()

    while( len(rand_set) < total_nums ):
        rand_set.add( random.uniform(lower_bound, upper_bound) )

    return rand_set

a = get_rand_array(1.0, 1.2, 5)
print( str(a) )

In each iteration, generate a random number in the desired range and add it to a set which makes sure that every element in it is unique

Method 2:

import random

def get_random_array(lower_limit, upper_limit, total_nums):
    rand_array = []

    while( len(rand_array) < total_nums ):
        current_rand = random.uniform(lower_limit, upper_limit)

        if( current_rand not in rand_array ):

    return rand_array

a = get_random_array(3.0, 3.1, 5)
print( str(a) )

Instead of using set as in method 1, in each iteration, check if the current_rand is already present in rand_array; if absent, append it to rand_array, which ensures unique elements in rand_array.

This is a lot easier if you have numpy.

import numpy as np

[22.31472037 90.3789552  28.4565216  34.79490853 16.48289675 39.15659334
 15.63986831 24.15726628  3.0404023  16.43198165]
>>> import random
>>> n = 5
>>> a, b = 0., 10.
>>> [random.uniform(a, b) for _ in range(n)]

If you're worried about uniqueness, you can compute the odd of finding a duplicate. It's given by the following relationship:

p(n,d) = 1 - e ** (-n**2/(2*d))

Where d is 2**52 and n the number of random numbers to be generated. For a thousand values, the probability is 1.11e-10. That means you're 64 times more likely to become a millionaire with a lottery ticket than finding a duplicate in this list.

Not the answer you're looking for? Browse other questions tagged or ask your own question.