Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly generate integers with a distribution that prefers low ones

Tags:

python

random

I have an list ordered by some quality function from which I'd like to take elements, preferring the good elements at the beginning of the list.

Currently, my function to generate the random indices looks essentially as follows:

def pick():
    p = 0.2
    for i in itertools.count():
        if random.random() < p:
            break
    return i

It does a good job, but I wonder:

  1. What's the name of the generated random distribution?
  2. Is there a built-in function in Python for that distribution?
like image 718
Michael Avatar asked Jan 28 '26 05:01

Michael


1 Answers

What you are describing sounds a lot like the exponential distribution. It already exists in the random module.

Here is some code that takes just the integer part of sampling from an exponential distribution with a rate parameter of 100.

import random
import matplotlib.pyplot as plt

d = [int(random.expovariate(1/100)) for i in range(10000)]
h,b = np.histogram(d, bins=np.arange(0,max(d)))

plt.bar(left=b[:-1], height=h, ec='none', width=1))
plt.show()

enter image description here

like image 98
James Avatar answered Jan 29 '26 18:01

James