Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Generating Random Numbers

Open in Colab

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.

Random 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.

Generator(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 [0,1)[0, 1): it can return 0 but never 1.

Pass a shape to get an array of random numbers. rng.uniform(a, b, size) samples uniformly from [a,b)[a, b):

Normal distribution

rng.standard_normal samples from the standard normal (Gaussian) distribution, which has mean 0 and variance 1:

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:

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:

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 1/λ1/\lambda, which is the mean, rather than the rate λ\lambda:

scipy.stats provides even more distributions. Their rvs method draws samples, and accepts a generator as its random_state argument:

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:

rng.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:

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:

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:

These 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 Generator is passed explicitly to the code that uses it.

  • Generator uses better algorithms. PCG64 has better statistical properties, and Generator uses faster methods for many distributions, including the normal and exponential distributions.

  • Generator can create independent streams of random numbers for parallel computations.

Translating legacy code is mostly mechanical:

legacyGenerator
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:

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:

Instead, create one generator at the start of the program and pass it to the functions that need random numbers