Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Generating Random Numbers

Open in Colab

Numpy provides several functions for generating random numbers. Documentation can be found here.

Populating the interactive namespace from numpy and matplotlib

Uniform Distrubution

np.random.rand samples double precision numbers in the range [0,1] uniformly at random.

0.1684372512782496

To generate an array of random numbers:

array([[0.06547767, 0.79321455], [0.12412586, 0.17844781]])

Gaussian Distribution

np.random.randn samples double precision numbers from a Gaussian (normal) distribution

0.38324242962418337

Again, an array of random numbers can be generated:

array([[-1.24202748, -0.19533947], [ 0.12978598, 0.83428311]])

Random Integers

np.random.randint samples inegers

7

to sample and array, size must be specified

array([[9, 9], [9, 7]])

Distributions in Scipy

While numpy provides basic random number generation capabilities, it does not provide utilities for sampling from more complex distribitions.

scipy.stats provides classes for a variety of commonly-used distributions - see the documentation

You can sample from the distribution using the rvs method

array([2, 2, 0, 2, 3])