This notebook is an element of the risk-engineering.org courseware. It can be distributed under the terms of the Creative Commons Attribution-ShareAlike licence.

Author: Eric Marsden eric.marsden@risk-engineering.org

This notebook contains an introduction to the use of SciPy library's support for various probability distributions. The library documentation is available online. We also show how the SymPy library for symbolic mathematics can be used to calculate various statistical properties analytically.

In :
import numpy
import scipy.stats
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%config InlineBackend.figure_formats=['svg']


Uniform distribution¶

Let’s generate 5 random variates from a continuous uniform distribution between 90 and 100 (the first argument to the scipy.stats.uniform function is the lower bound, and the second argument is the width). The object u will contain the “frozen distribution”.

In :
u = scipy.stats.uniform(90, 10)
u.rvs(5)

Out:
array([95.19904417, 94.48788122, 95.55792962, 91.12148563, 97.94822251])

Let’s check that the expected value of the distribution is around 95.

In :
u.rvs(1000).mean()

Out:
94.94941825440037

Let’s check that around 20% of the variates are less than 92.

In :
(u.rvs(1000) < 92).sum() / 1000.0

Out:
0.213

We can also use the stats module of the SymPy library to obtain the same information using an analytical (rather than stochastic) method.

In :
import sympy.stats

us = sympy.stats.Uniform("unif", 90, 100)
# generate one random variate
sympy.stats.sample(us)

Out:
96.6040709751020

Check that the expected value (the mean of the distribution) is 95.

In :
sympy.stats.E(us)

Out:
95

The probability of a random variate being less than 92:

In :
sympy.stats.P(us < 92)

Out:
1/5

Gaussian distribution¶

Consider a Gaussian (normal) distribution centered in 5, with a standard deviation of 1.

In :
norm = scipy.stats.norm(5, 1)
x = numpy.linspace(1, 9, 100)
plt.plot(x, norm.pdf(x));


Check that half the distribution is located to the left of 5.

In :
norm.cdf(5)

Out:
0.5
In :
norm.ppf(0.5)

Out:
5.0

Find the first percentile of the distribution (the value of $x$ which has 1% of realizations to the left). Check that it is also equal to the 99% survival quantile.

In :
norm.ppf(0.01)

Out:
2.6736521259591592
In :
norm.isf(0.99)

Out:
2.6736521259591592
In :
norm.cdf(norm.isf(0.99))

Out:
0.01

We can also execute some calculations on the normal distribution analytically, using the SymPy library.

In :
z = sympy.Symbol("z")
Norm = sympy.stats.Normal('Gaussian', 5, 1)
sympy.stats.density(Norm)(z)

Out:
sqrt(2)*exp(-(z - 5)**2/2)/(2*sqrt(pi))
In :
# we ask for the evaluation to 30 significant figures
sympy.stats.density(Norm)(4).evalf(30)

Out:
0.241970724519143349797830192936
In :
norm.pdf(4)

Out:
0.24197072451914337
In :
# check that half of our distribution is greater than 5 (this is equivalent to the CDF(5))
sympy.stats.P(Norm > 5)

Out:
1/2
In :
# check that the expected value (the mean) is 5
sympy.stats.E(Norm)

Out:
5

Central limit theorem¶

The central limit theorem states that the mean of a set of random measurements will tend to a normal distribution, no matter the shape of the original measurement distribution. The property is also true of the sum of a set of random measurements. Let's test that in Python, simulating measurements from a uniform distribution between 30 and 40.

Procedure: take 100 measurements from the $U(30, 40)$ distribution, and calculate their mean. Repeat this 10000 times and plot a histogram of the means, which should be normally distributed.

In :
N = 10000
sim = numpy.zeros(N)
for i in range(N):
sim[i] = numpy.random.uniform(30, 40, 100).mean()
plt.hist(sim, bins=20, alpha=0.5, density=True);


Exercise: try this with other probability distributions.

Exponential distribution¶

The exponential distribution is often used in reliability engineering to represent failure of equipment which is not exposed to wear. The hazard function, or failure rate, of the exponential distribution is constant, equal to $\lambda$. Let's check the property that the expected value (or mean) of an exponential random variable is $\frac{1}{\lambda}$.

In :
lbda = 25
obs = scipy.stats.expon(scale=1/float(lbda)).rvs(size=1000)
# the mean of 1000 random variates from the exponential distribution
obs.mean()

Out:
0.039447791622287454
In :
1/float(lbda)

Out:
0.04

Indeed, those are quite close! Let’s check another property of the exponential distribution: that the variance is equal to $\lambda^{-2}$.

In :
obs.var()

Out:
0.0016537060643875702
In :
1/float(lbda)**2

Out:
0.0016

And of course since the standard deviation is the square root of the variance, it should be equal to the expected value.

In :
obs.std()

Out:
0.0406657849350971

As previously, we can also check these properties analytically, using the SymPy symbolic mathematics library, starting with the expected value:

In :
exps = sympy.stats.Exponential("exp", lbda)
sympy.stats.E(exps)

Out:
1/25
In :
# now check that the variance is lambda ^ -2
sympy.stats.variance(exps) - lbda**-2

Out:
0
In :
# check that the standard deviation is equal to the expectation
sympy.stats.std(exps) - sympy.stats.E(exps)

Out:
0
In [ ]: