Numpy provides several functions for generating random numbers. Documentation can be found here.
%pylab inline
import numpy as np
import scipy.stats as statsPopulating 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.1684372512782496To generate an array of random numbers:
np.random.rand(2,2)array([[0.06547767, 0.79321455],
[0.12412586, 0.17844781]])Gaussian Distribution¶
np.random.randn samples double precision numbers from a Gaussian (normal) distribution
np.random.randn()0.38324242962418337Again, an array of random numbers can be generated:
np.random.randn(2,2)array([[-1.24202748, -0.19533947],
[ 0.12978598, 0.83428311]])Random Integers¶
np.random.randint samples inegers
np.random.randint(10)7to sample and array, size must be specified
np.random.randint(10, size=(2,2))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
import scipy.stats as statsd = stats.poisson(2.0)You can sample from the distribution using the rvs method
d.rvs(5)array([2, 2, 0, 2, 3])