Random Number Generation
Random number generation is a central task of Monte Carlo simulation.
[ 71 ]
Chapter 10
shows how to use Python and libraries such as numpy.random to generate random numbers
with different distributions. For our project at hand, standard normally distributed random
numbers are the most important ones. That is why it pays off to have a convenience
function available for generating this particular type of random numbers. Example 16-1
presents such a function.
Example 16-1. Function to generate standard normally distributed random numbers
import numpy as np
def sn_random_numbers(shape, antithetic=True, moment_matching=True,
fixed_seed=False):
”’ Returns an array of shape shape with (pseudo)random numbers
that are standard normally distributed.
Parameters
==========
shape : tuple (o, n, m)
generation of array with shape (o, n, m)
antithetic : Boolean
generation of antithetic variates
moment_matching : Boolean
matching of first and second moments
fixed_seed : Boolean
flag to fix the seed
Results
=======
ran : (o, n, m) array of (pseudo)random numbers
”’
if fixed_seed:
np.random.seed( 1000 )
if antithetic:
ran = np.random.standard_normal((shape[ 0 ], shape[ 1 ], shape[ 2 ] / 2 ))
ran = np.concatenate((ran, -ran), axis= 2 )
else:
ran = np.random.standard_normal(shape)
if moment_matching:
ran = ran - np.mean(ran)
ran = ran / np.std(ran)
if shape[ 0 ] == 1 :
return ran[ 0 ]
else:
return ran
The variance reduction techniques used in this function, namely antithetic paths and
moment matching, are also illustrated in Chapter 10.
[ 72 ]
The application of the function is straightforward:
In [ 1 ]: from sn_random_numbers import *
In [ 2 ]: snrn = sn_random_numbers(( 2 , 2 , 2 ), antithetic=False,
...: moment_matching=False,
...: fixed_seed=True)
In [ 3 ]: snrn
Out[ 3 ]:
array([[[-0.8044583 , 0.32093155],
[-0.02548288, 0.64432383]],
[[-0.30079667, 0.38947455],
[-0.1074373 , -0.47998308]]])
In [ 4 ]: snrn_mm = sn_random_numbers(( 2 , 3 , 2 ), antithetic=False,
...: moment_matching=True,