summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authorCharles Harris <charlesr.harris@gmail.com>2020-07-13 10:40:42 -0600
committerGitHub <noreply@github.com>2020-07-13 10:40:42 -0600
commitdd883ce53d0744c616de472215287d680c660ac5 (patch)
treee71809cffd275a08ae7ff75908448ab831f0fe00 /numpy
parent18ee184cd82cc961be64ada15683438181eacfcd (diff)
parentf986a00c8dfc1501df8a311d421cb016817f4efc (diff)
downloadnumpy-dd883ce53d0744c616de472215287d680c660ac5.tar.gz
Merge pull request #16824 from lastephey/add-rng-examples
DOC: add examples to random number generator pages
Diffstat (limited to 'numpy')
-rw-r--r--numpy/random/_generator.pyx53
1 files changed, 53 insertions, 0 deletions
diff --git a/numpy/random/_generator.pyx b/numpy/random/_generator.pyx
index 0936ea2e8..cc2852da7 100644
--- a/numpy/random/_generator.pyx
+++ b/numpy/random/_generator.pyx
@@ -4349,6 +4349,59 @@ def default_rng(seed=None):
-----
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 reccomended 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 numpy as np
+ >>> rng = np.random.default_rng(12345)
+ >>> print(rng)
+ Generator(PCG64)
+ >>> rfloat = rng.random()
+ >>> rfloat
+ 0.22733602246716966
+ >>> type(rfloat)
+ <class 'float'>
+
+ Here we use ``default_rng`` to generate 3 random integers between 0
+ (inclusive) and 10 (exclusive):
+
+ >>> import numpy as np
+ >>> rng = np.random.default_rng(12345)
+ >>> rints = rng.integers(low=0, high=10, size=3)
+ >>> rints
+ array([6, 2, 7])
+ >>> type(rints[0])
+ <class 'numpy.int64'>
+
+ Here we specify a seed so that we have reproducible results:
+
+ >>> import numpy as np
+ >>> rng = np.random.default_rng(seed=42)
+ >>> print(rng)
+ Generator(PCG64)
+ >>> arr1 = rng.random((3, 3))
+ >>> arr1
+ array([[0.77395605, 0.43887844, 0.85859792],
+ [0.69736803, 0.09417735, 0.97562235],
+ [0.7611397 , 0.78606431, 0.12811363]])
+
+ If we exit and restart our Python interpreter, we'll see that we
+ generate the same random numbers again:
+
+ >>> import numpy as np
+ >>> rng = np.random.default_rng(seed=42)
+ >>> arr2 = rng.random((3, 3))
+ >>> arr2
+ array([[0.77395605, 0.43887844, 0.85859792],
+ [0.69736803, 0.09417735, 0.97562235],
+ [0.7611397 , 0.78606431, 0.12811363]])
+
"""
if _check_bit_generator(seed):
# We were passed a BitGenerator, so just wrap it up.