Skip to content Skip to sidebar Skip to footer

Random Number With Given Pdf In Python

I want to generate an integer random number with a probability distribution function given as a list. For example if pdf=[3,2,1] then I like rndWDist(pdf) to return

Solution 1:

This is a duplicate question: Generate random numbers with a given (numerical) distribution

As the first answer there suggest, you might want to use scipy.stats.rv_discrete.

You might use it like that:

from scipy.stats import rv_discrete
numbers = (1,2,3)
distribution = (1./6, 2./6, 3./6)
random_variable = rv_discrete(values=(numbers,distribution))
random_variable.rvs(size=10)

This returns a numpy array with 10 random values.

Solution 2:

Given the format of your input, you could do:

defrandint_with_dist(pdf):
    choices = []
    for index, value inenumerate(pdf):
        choices.extend(index for _ inrange(value))
    return random.choice(choices)

As the same list will be used every time the same pdf is passed, you could consider caching the list for greater efficiency (at the cost of space):

defrandint_with_dist(pdf, choices={}):
    pdf = tuple(pdf)
    if pdf notin choices:
        choices[pdf] = []
        for index, value inenumerate(pdf):
            choices[pdf].extend(index for _ inrange(value))
    return random.choice(choices[pdf])

Solution 3:

Using numpy (version 1.7 or newer), you could also use np.random.choice:

In [27]: import numpy as np

In [28]: distribution = (1./6, 2./6, 3./6)

In [29]: np.random.choice(np.arange(len(distribution)), p=distribution)
Out[29]: 0

In [30]: np.random.choice(np.arange(len(distribution)), p=distribution, size=10)
Out[30]: array([2, 1, 1, 2, 2, 0, 1, 0, 1, 0])

Post a Comment for "Random Number With Given Pdf In Python"