Search code examples
pythonrandom

Randomly picking numbers from a list according to a uniform distribution


I have a list as such

a = [.5,.57,.67,.8,1,1.33,2,4]

Which looks like this when plotted: enter image description here

I need to randomly pick a number in this list. In Python, I would normally go like this:

c = random.choice(a)

Except... Doing this biases the pick towards a lower value (the density is higher around 1 than it is around 4).

How would I go about picking a list entry according to a uniform distribution. As in c = random.random()*3.5+.5, but actually picking from the list?


Solution

  • You could get floats from an uniform distribution and then choosing the one on your list that's closest to this generated value. Like so:

    a = [.5,.57,.67,.8,1,1.33,2,4]
    p = list(map(lambda x: abs(random.uniform(0,4) - x), a))
    c = a[p.index(min(p))]
    

    Of course, you could do it more efficently given that your list is sorted.