Link Search Menu Expand Document (external link)

How to generate random values from a distribution (in Python, using SciPy)

See all solutions.

Task

There are many famous continuous probability distributions, such as the normal and exponential distributions. How can we get access to them in software, to generate random values from a chosen distribution?

Related tasks:

Solution

You can import many different random variables from SciPy’s stats module. The full list of them is online here.

Regardless of whether the distribution is discrete or continuous, the appropriate function to call is rvs, which stands for “random values.” Here are two examples.

Using a normal distribution:

1
2
3
from scipy import stats
X = stats.norm( 10, 5 )  # normal random variable with μ=10 and σ=5
X.rvs( 20 )              # 20 random values from X
1
2
3
4
array([10.6907129 , 14.18269263, 11.81631776,  8.01109692, 13.02531043,
        7.81131811, 13.28578636, 11.24026458, 11.15153426, 17.88676989,
       19.31140617,  9.6059965 , 12.1120152 , 19.4371871 , 11.20087368,
        8.82303356, 20.84662811,  0.3140319 , 16.45965892,  8.64633779])

Using a uniform distribution:

(Note that in SciPy, the uniform distribution needs a “location,” which is where the sample space begins—in this case 50—and a “scale,” which is the width of the sample space—in this case 10.)

1
2
3
from scipy import stats
X = stats.uniform( 50, 10 )  # uniform random variable on the interval [50,60]
X.rvs( 20 )                  # 20 random values from X
1
2
3
4
array([55.45216751, 51.33233834, 52.95952577, 50.73167814, 58.03758018,
       51.92018223, 56.50131882, 51.17126188, 54.57665328, 57.67945112,
       52.70825309, 56.02047417, 59.47625062, 52.09755942, 54.7246222 ,
       54.71473066, 59.81365965, 59.2618776 , 54.9747678 , 50.74177568])

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)