How do I generate Log Uniform Distribution in Python?

jkrish picture jkrish · May 15, 2017 · Viewed 16k times · Source

I could not find a built-in function in Python to generate a log uniform distribution given a min and max value (the R equivalent is here), something like: loguni[n, exp(min), exp(max), base] that returns n log uniformly distributed in the range exp(min) and exp(max).

The closest I found though was numpy.random.uniform.

Answer

Scott Gigante picture Scott Gigante · May 15, 2017

From http://ecolego.facilia.se/ecolego/show/Log-Uniform%20Distribution:

In a loguniform distribution, the logtransformed random variable is assumed to be uniformly distributed.

Thus

logU(a, b) ~ exp(U(log(a), log(b))

Thus, we could create a log-uniform distribution using numpy:

def loguniform(low=0, high=1, size=None):
    return np.exp(np.random.uniform(low, high, size))

If you want to choose a different base, we could define a new function as follows:

def lognuniform(low=0, high=1, size=None, base=np.e):
    return np.power(base, np.random.uniform(low, high, size))

EDIT: @joaoFaria's answer is also correct.

def loguniform(low=0, high=1, size=None):
    return scipy.stats.reciprocal(np.exp(low), np.exp(high)).rvs(size)