What’s new or different#

NumPy 1.17.0 introduced Generator as an improved replacement for the legacy RandomState. Here is a quick comparison of the two implementations.

Feature

Older Equivalent

Notes

Generator

RandomState

Generator requires a stream source, called a BitGenerator A number of these are provided. RandomState uses the Mersenne Twister MT19937 by default, but can also be instantiated with any BitGenerator.

random

random_sample, rand

Access the values in a BitGenerator, convert them to float64 in the interval [0.0., 1.0). In addition to the size kwarg, now supports dtype='d' or dtype='f', and an out kwarg to fill a user-supplied array.

Many other distributions are also supported.

integers

randint, random_integers

Use the endpoint kwarg to adjust the inclusion or exclusion of the high interval endpoint.

In [1]: rng = np.random.default_rng()

In [2]: rng.random(3, dtype=np.float64)
Out[2]: array([0.77395605, 0.43887844, 0.85859792])

In [3]: rng.random(3, dtype=np.float32)
Out[3]: array([0.08594561, 0.697368  , 0.20146948], dtype=float32)

In [4]: rng.integers(0, 256, size=3, dtype=np.uint8)
Out[4]: array([181,   1,  28], dtype=uint8)
  • Optional out argument that allows existing arrays to be filled for select distributions

    This allows multithreading to fill large arrays in chunks using suitable BitGenerators in parallel.

In [5]: rng = np.random.default_rng()

In [6]: existing = np.zeros(4)

In [7]: rng.random(out=existing[:2])
Out[7]: array([0.77395605, 0.43887844])

In [8]: print(existing)
[0.77395605 0.43887844 0.         0.        ]
  • Optional axis argument for methods like choice, permutation and shuffle that controls which axis an operation is performed over for multi-dimensional arrays.

In [9]: rng = np.random.default_rng()

In [10]: a = np.arange(12).reshape((3, 4))

In [11]: a
Out[11]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [12]: rng.choice(a, axis=1, size=5)
Out[12]: 
array([[ 0,  3,  2,  1,  1],
       [ 4,  7,  6,  5,  5],
       [ 8, 11, 10,  9,  9]])

In [13]: rng.shuffle(a, axis=1)        # Shuffle in-place

In [14]: a
Out[14]: 
array([[ 3,  0,  1,  2],
       [ 7,  4,  5,  6],
       [11,  8,  9, 10]])
  • Added a method to sample from the complex normal distribution (complex_normal)