How do I generate Log Uniform Distribution in Python?
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)
SciPy v1.4 includes a loguniform
random variable: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.loguniform.html
Here's how to use it:
from scipy.stats import loguniform
rvs = loguniform.rvs(1e-2, 1e0, size=1000)
This will create random variables evenly spaced between 0.01 and 1. That best shown by visualizing the log-scaled histogram:
This "log-scaling" works regardless of base; loguniform.rvs(2**-2, 2**0, size=1000)
also produces log-uniform random variables. More details are in loguniform
's documentation.