Random numbers are used throughout scientific computing. A computer runs a deterministic program, so the numbers it produces are pseudorandom: a deterministic sequence designed to be statistically indistinguishable from truly random numbers.
This section shows how to use NumPy’s random number generators (documentation), how the generators work, and how uniform random numbers are turned into samples from other distributions.
import copy
import secrets
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.special import gamma
from scipy.stats import qmcRandom numbers in NumPy¶
NumPy draws random numbers from a generator object, created by np.random.default_rng.
The argument is a seed, which we discuss below; any integer will do.
rng = np.random.default_rng(37830)
rngGenerator(PCG64) means that the generator gets its random bits from an algorithm called PCG64. We draw random numbers by calling methods of rng.
Uniform distribution¶
rng.random samples double precision numbers uniformly from the half-open interval :
it can return 0 but never 1.
rng.random()Pass a shape to get an array of random numbers. rng.uniform(a, b, size) samples uniformly
from :
print(rng.random((2, 3)))
print(rng.uniform(-1, 1, size=3))Normal distribution¶
rng.standard_normal samples from the standard normal (Gaussian) distribution, which has mean 0
and variance 1:
rng.standard_normal((2, 2))rng.normal(loc, scale, size) samples from the normal distribution with mean loc and standard
deviation scale. Note that scale is the standard deviation, not the variance:
x = rng.normal(loc=5.0, scale=2.0, size=100_000)
print(f"sample mean {x.mean():.3f}, sample standard deviation {x.std():.3f}")Random integers¶
rng.integers(low, high, size) samples integers uniformly from low, low + 1, ..., high - 1.
As with range, high is excluded unless you pass endpoint=True. Here are ten rolls of a
die:
rng.integers(1, 7, size=10) # equivalent to rng.integers(1, 6, size=10, endpoint=True)Other distributions¶
Generator has methods for many other distributions, listed in the
documentation.
Check how a distribution is parameterized before you use it. For example, rng.exponential
takes the scale , which is the mean, rather than the rate :
lam = 4.0
x = rng.exponential(scale=1 / lam, size=100_000)
print(f"sample mean {x.mean():.4f}, 1 / lambda = {1 / lam:.4f}")scipy.stats provides even more distributions. Their rvs method draws
samples, and accepts a generator as its random_state argument:
d = stats.poisson(2.0)
d.rvs(size=5, random_state=rng)Sampling from an array, and shuffling¶
rng.choice draws elements of an array, with replacement unless you pass replace=False. The
optional argument p gives the elements different probabilities:
print(rng.choice(['rock', 'paper', 'scissors'], size=5))
print(rng.choice(52, size=5, replace=False)) # 5 different cards from a deck of 52
print(rng.choice(['heads', 'tails'], size=10, p=[0.7, 0.3])) # a biased coinrng.permutation(n) returns a random ordering of 0, 1, ..., n - 1, and rng.shuffle(x)
shuffles the array x in place. A random permutation is an easy way to split a data set into a
training set and a test set:
order = rng.permutation(10)
train, test = order[:8], order[8:]
print("train:", np.sort(train), " test:", np.sort(test))Draw many numbers at once¶
Every call to a Generator method has a fixed overhead that is much larger than the cost of
generating one number. As with other NumPy functions, asking for a whole array at once is much
faster than calling the method in a Python loop:
n = 10**6
start = time.perf_counter()
x_loop = [rng.random() for _ in range(n)]
loop = time.perf_counter() - start
start = time.perf_counter()
x = rng.random(n)
one_call = time.perf_counter() - start
print(f"loop: {loop:.3f} s, one call: {one_call:.4f} s ({loop / one_call:.0f} times faster)")A simulation that needs random numbers at every time step can still draw them in bulk, for all the paths at once.
The legacy interface¶
Older code, including some of the class notes, calls functions in np.random directly:
np.random.seed(0)
print(np.random.rand(3)) # uniform on [0, 1)
print(np.random.randn(3)) # standard normal
print(np.random.randint(10, size=3)) # integers 0, ..., 9These functions all use a single hidden, global generator, and np.random.seed seeds it. They still work, and for
backward compatibility NumPy keeps their output for a given seed fixed, but NumPy recommends
Generator for new code:
The global generator is shared by all the code in a program. A library function that draws random numbers changes the numbers your own code gets next, and it is hard to tell which code used which numbers. A
Generatoris passed explicitly to the code that uses it.Generatoruses better algorithms. PCG64 has better statistical properties, andGeneratoruses faster methods for many distributions, including the normal and exponential distributions.Generatorcan create independent streams of random numbers for parallel computations.
Translating legacy code is mostly mechanical:
| legacy | Generator |
|---|---|
np.random.seed(s) | rng = np.random.default_rng(s) |
np.random.rand(m, n) | rng.random((m, n)) |
np.random.randn(m, n) | rng.standard_normal((m, n)) |
np.random.randint(low, high, size) | rng.integers(low, high, size) |
np.random.normal, np.random.choice, ... | rng.normal, rng.choice, ... |
The two interfaces use different algorithms, so the same seed gives different numbers. Python’s
built-in random module is yet another
generator.
Seeds and reproducibility¶
Generators created with the same seed produce the same numbers:
print(np.random.default_rng(42).random(3))
print(np.random.default_rng(42).random(3))
print(np.random.default_rng(43).random(3))Without a seed, np.random.default_rng() gets its seed from the operating system’s source of
randomness, and every run of the program gives different numbers.
A fixed seed makes a computation reproducible: running it again gives exactly the same result.
A common mistake is to create a seeded generator inside a function. Then every call starts from the same state and gets the same “random” numbers:
def noisy_measurement(x):
rng = np.random.default_rng(0) # wrong: a new generator in the same state on every call
return x + 0.1 * rng.standard_normal()
[noisy_measurement(1.0) for _ in range(3)]Instead, create one generator at the start of the program and pass it to the functions that need random numbers
rng = np.random.default_rng(0)
def noisy_measurement(x, rng):
return x + 0.1 * rng.standard_normal()
[noisy_measurement(1.0, rng) for _ in range(3)]