Numpy random number generators#
#: standard imports
import numpy as np
# print arrays to 4 decimal places
np.set_printoptions(precision=4, suppress=True)
We often need random numbers, for tests and for taking random samples, and for
other things. np.random
is a submodule within numpy:
type(np.random)
module
It contains function that will create a random number generator.
# Make a random number generator.
rng = np.random.default_rng()
type(rng)
numpy.random._generator.Generator
This generator is an object that has a set of methods for returning random numbers of various sorts. For example, to return a single random number from the default normal distribution (mean 0, variance 1):
rng.normal()
0.1561313253150664
You can set the mean and variance with the first two input parameters:
# Random number from distribution with mean 15, variance 2
rng.normal(15, 2)
17.283947497270667
To return a 8 by 5 array of random numbers from the same distribution:
rng.normal(15, 2, size=(8, 5))
array([[14.5994, 9.7962, 16.2723, 16.752 , 17.5274],
[14.8919, 18.1976, 11.4291, 12.2943, 17.4066],
[14.649 , 9.7467, 15.0475, 16.0897, 10.9309],
[14.8456, 11.4277, 13.2358, 19.0015, 17.5183],
[17.4964, 17.6885, 8.1901, 13.7035, 15.9571],
[14.7317, 17.8072, 17.5164, 15.8536, 10.639 ],
[18.3061, 12.8098, 15.2429, 13.2912, 13.2401],
[13.8735, 15.6828, 13.8814, 16.8983, 14.55 ]])
A 5 by 3 array of random numbers from the standard normal distribution with mean 1 and variance 1:
rng.normal(size=(5, 3))
array([[ 0.2159, 0.7549, -0.6959],
[ 0.4839, -0.0873, -1.5388],
[ 0.3123, -0.0434, 1.2928],
[-0.3932, -0.5191, 1.1985],
[ 0.5762, -0.4437, -0.7948]])
Making random numbers predictable#
Sometimes you want to make sure that the random numbers are predictable, in
that you will always get the same set of random numbers from a series of calls
to the rng
methods. You can achieve this by giving the random number
generator a seed when you create it. This is an integer that sets the
random number generator into a predictable state, such that it will always
return the same sequence of random numbers from this point:
# Set the state of the random number generator on creation.
new_rng = np.random.default_rng(seed=42)
# One set of random numbers
first_random_arr = new_rng.normal(size=(4, 2))
first_random_arr
array([[ 0.3047, -1.04 ],
[ 0.7505, 0.9406],
[-1.951 , -1.3022],
[ 0.1278, -0.3162]])
# Another set
second_random_arr = new_rng.normal(size=(4, 2))
second_random_arr
array([[-0.0168, -0.853 ],
[ 0.8794, 0.7778],
[ 0.066 , 1.1272],
[ 0.4675, -0.8593]])
# Make another random number generator with the same seed.
new_rng2 = np.random.default_rng(seed=42)
# The same as "first_random_arr" above.
new_rng2.normal(size=(4, 2))
array([[ 0.3047, -1.04 ],
[ 0.7505, 0.9406],
[-1.951 , -1.3022],
[ 0.1278, -0.3162]])
# The same as "second_random_arr" above.
new_rng2.normal(size=(4, 2))
array([[-0.0168, -0.853 ],
[ 0.8794, 0.7778],
[ 0.066 , 1.1272],
[ 0.4675, -0.8593]])