Chapter 7: Miscellaneous

Random number generation

face Josiah Wang

To generate random numbers in NumPy, you should first import the Default Random Number Generator provided by NumPy.

>>> from numpy.random import default_rng

You should then initialise the random number generator with a seed number (just choose any number).

>>> seed = 7777
>>> rg = default_rng(seed)

Random numbers are not really random in computers. They are pseudo-random because you can reproduce the same ‘random’ sequence with a fixed seed number. This is important in your scientific experiments so that you can reproduce your experimental results!

You can then use the random generator instance to generate random numbers or arrays.

>>> x = rg.random((5, 3))
>>> print(x)
[[0.94192575 0.59573376 0.58880255]
 [0.71400906 0.24578678 0.63006854]
 [0.26233112 0.39487634 0.65615324]
 [0.85818932 0.20564809 0.9837931 ]
 [0.18541645 0.67159972 0.99064663]]
>>> y = rg.integers(1, 10, size=(5,3)) # Random integers from 1 to 10 (exclusive)
print(y)
[[9 8 7]
 [7 2 8]
 [9 9 4]
 [1 9 6]
 [6 3 3]]

Please refer to the official documentation for all the possible distributions from which you can randomly sample! The different distributions are listed towards the end of the page.