Search code examples
pythonrandomfrequency-distribution

Random numbers that follow a linear drop distribution in Python


I'd like to generate random numbers that follow a dropping linear frequency distribution, take n=1-x for an example.

The numpy library however seems to offer only more complex distributions.


Solution

  • So, it turns out you can totally use random.triangular(0,1,0) for this. See documentation here: https://docs.python.org/2/library/random.html

    random.triangular(low, high, mode)

    Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds.

    Histogram made with matplotlib:

    import matplotlib.pyplot as plt
    import random
    bins = [0.1 * i for i in range(12)]
    plt.hist([random.triangular(0,1,0) for i in range(2500)], bins)
    

    enter image description here