dask.array.random.default_rng

dask.array.random.default_rng

dask.array.random.default_rng(seed=None)[source]

Construct a new Generator with the default BitGenerator (PCG64).

Parameters
seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Additionally, when passed a BitGenerator, it will be wrapped by Generator. If passed a Generator, it will be returned unaltered.

Returns
Generator

The initialized generator object.

See also

np.random.default_rng

Notes

If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated. This function does not manage a default global instance.

Examples

default_rng is the recommended constructor for the random number class Generator. Here are several ways we can construct a random number generator using default_rng and the Generator class.

Here we use default_rng to generate a random float:

>>> import dask.array as da
>>> rng = da.random.default_rng(12345)
>>> print(rng)
Generator(PCG64)
>>> rfloat = rng.random().compute()
>>> rfloat
array(0.86999885)
>>> type(rfloat)
<class 'numpy.ndarray'>

Here we use default_rng to generate 3 random integers between 0 (inclusive) and 10 (exclusive):

>>> import dask.array as da
>>> rng = da.random.default_rng(12345)
>>> rints = rng.integers(low=0, high=10, size=3).compute()
>>> rints
array([2, 8, 7])
>>> type(rints[0])
<class 'numpy.int64'>

Here we specify a seed so that we have reproducible results:

>>> import dask.array as da
>>> rng = da.random.default_rng(seed=42)
>>> print(rng)
Generator(PCG64)
>>> arr1 = rng.random((3, 3)).compute()
>>> arr1
array([[0.91674416, 0.91098667, 0.8765925 ],
       [0.30931841, 0.95465607, 0.17509458],
       [0.99662814, 0.75203348, 0.15038118]])

If we exit and restart our Python interpreter, we’ll see that we generate the same random numbers again:

>>> import dask.array as da
>>> rng = da.random.default_rng(seed=42)
>>> arr2 = rng.random((3, 3)).compute()
>>> arr2
array([[0.91674416, 0.91098667, 0.8765925 ],
       [0.30931841, 0.95465607, 0.17509458],
       [0.99662814, 0.75203348, 0.15038118]])