0

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.

Ofek S.
  • 51
  • 1
  • 12
humble
  • 2,016
  • 4
  • 27
  • 36
  • 1
    So, what have you tried? – Ulrich Eckhardt Jan 14 '18 at 09:23
  • 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 – humble Jan 14 '18 at 09:27
  • 2
    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 Jan 14 '18 at 09:33

3 Answers3

2

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.

Saketh Katari
  • 332
  • 2
  • 11
1
>>> import random
>>> n = 5
>>> a, b = 0., 10.
>>> [random.uniform(a, b) for _ in range(n)]
[1.1617037103617134,
 5.977376104342625,
 7.04027407732932,
 0.10349393354524894,
 2.3731423390045023]

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.

Vincent
  • 12,919
  • 1
  • 42
  • 64
0

This is a lot easier if you have numpy.

import numpy as np
x=np.random.uniform(1,100,10)
print(x)

[22.31472037 90.3789552  28.4565216  34.79490853 16.48289675 39.15659334
 15.63986831 24.15726628  3.0404023  16.43198165]