Random number generation

Slides for “Random number generation”

Control questions

  1. What is random?
  2. What do we call random numbers generated from an algorithm?
  3. Are these numbers truly random?
  4. What do mean when we say that numbers generated by the algorithms are deterministic?
  5. What does a setting a seed do?
  6. Can you explain the inverse transform sampling procedure?

Generate random numbers from a distribution

from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Generate 2000 random numbers from a uniform distribution: 
x = stats.uniform.rvs(size = 2000)
# Plot histogram of the simulated data: 
sns.histplot(x, stat = "density")
plt.show()
# Add uniform density function to the plot:
sns.histplot(x, stat = "density")
xvalues = np.linspace(0, 1, 2000)
pdf = stats.uniform.pdf(xvalues)
plt.plot(xvalues, pdf, color = "red")
plt.show()

It is often a good idea to set a seed when generating random numbers. This has the benefit that every time you rerun your code, the same random random are generated. If you want a new draw from the distribution, you change the seed and you will get a new set of numbers. Test this out your self using the code below:

np.random.seed(123)
x = stats.uniform.rvs(size = 5)
print(x)
np.random.seed(123)
x = stats.uniform.rvs(size = 5)
print(x)
np.random.seed(124)
x = stats.uniform.rvs(size = 5)
print(x)
[0.69646919 0.28613933 0.22685145 0.55131477 0.71946897]
[0.69646919 0.28613933 0.22685145 0.55131477 0.71946897]
[0.10606491 0.74547148 0.57231354 0.45824118 0.3847059 ]