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 ):
rand_array.append(current_rand)
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
.