Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Number in Range from Single-Tailed Distribution with Python

I want to generate a random float in the range [0, 1) from a one-tailed distribution that looks like this enter image description here

The above is the chi-squared distribution. I can only find resources on drawing from a uniform distribution in a range, however.

like image 648
taurus Avatar asked Jan 23 '26 22:01

taurus


1 Answers

You could use a Beta distribution, e.g.

import numpy as np

np.random.seed(2018)
np.random.beta(2, 5, 10)
#array([ 0.18094173,  0.26192478,  0.14055507,  0.07172968,  0.11830031,
#        0.1027738 ,  0.20499125,  0.23220654,  0.0251325 ,  0.26324832])

Here we draw numbers from a Beta(2, 5) distribution

enter image description here

The Beta distribution is a very versatile and fundamental distribution in statistics; without going into any details, by changing the parameters alpha and beta you can make the distribution left-skewed, right-skewed, uniform, symmetric etc. The distribution is defined on the interval [0, 1] which is consistent with what you're after.


A more technical comment

While the Kumaraswamy distribution certainly has more benign algebraic properties than the Beta distribution I would argue that the latter is the more fundamental distribution; for example, in Bayesian inference, the Beta distribution often enters as the conjugate prior when dealing with binomial(-like) processes.

Secondly, the mean and variance of the Beta distribution can be expressed quite simply in terms of the parameters alpha, beta; for example, the mean is simply given by alpha / (alpha + beta).

Lastly, from a computational and statistical inference point of view, fitting a Beta distribution to data is usually done in a few lines of code in Python (or R), where most Python libraries like numpy and scipy already include methods to deal with the Beta distribution.

like image 124
Maurits Evers Avatar answered Jan 25 '26 10:01

Maurits Evers