Generating Random Numbers

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

%pylab inline
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.

np.random.rand()
0.08221563546580424

To generate an array of random numbers:

np.random.rand(2,2)
array([[0.85933325, 0.10024714],
       [0.48806348, 0.03033919]])

Gaussian Distribution

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

np.random.randn()
-2.7301323106947186

Again, an array of random numbers can be generated:

np.random.randn(2,2)
array([[-0.25273664,  0.46481441],
       [ 1.04734062,  1.83790601]])

Random Integers

np.random.randint samples inegers

np.random.randint(10)
1

to sample and array, size must be specified

np.random.randint(10, size=(2,2))
array([[5, 7],
       [4, 1]])

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

import scipy.stats as stats
d = stats.poisson(2.0)

You can sample from the distribution using the rvs method

d.rvs(5)
array([2, 2, 1, 4, 3])