Random Numbers & Sampling#

Every Monte Carlo price starts with random numbers, and several of the other methods in this series use them for checks. This page covers how they are generated, how a uniform number becomes a normal one, how correlation is added, and what quasi-random numbers are. It is the first page of the series, and the pages after it use only the tools set out here.

Pseudo-random numbers#

A computer does not produce random numbers. A pseudo-random generator is a deterministic rule that turns a seed into a long sequence of numbers that behave like independent draws from the uniform distribution on \((0, 1)\). Two properties matter in valuation:

  • Quality. The numbers pass statistical tests of uniformity and independence, and the sequence is far longer than any run. The default generator of NumPy, PCG64, and the older Mersenne Twister both meet this for pricing.

  • Reproducibility. The same generator and the same seed give the same numbers. A price that cannot be reproduced cannot be reviewed, so every run records the generator, the version and the seed.

For parallel runs each worker needs its own stream, and the streams must not overlap. Libraries provide this by spawning child streams from one seed. Giving each worker its own seed by hand, such as the numbers 1, 2, 3, is not safe for every generator.

From uniform to normal#

Almost every model needs normal draws, \(Z \sim N(0,1)\). Two standard routes start from uniform draws \(U\), \(U_1\) and \(U_2\).

Inverse transform. If \(F\) is the distribution function of the target, then \(F^{-1}(U)\) has that distribution. For the normal, \(Z = \Phi^{-1}(U)\). The method uses one uniform per normal, it works for any distribution with a known inverse, and it keeps the order of the uniform numbers. That last property is what quasi-random sequences need.

Box-Muller. Two independent uniforms give two independent normals:

\[Z_1 = \sqrt{-2 \ln U_1} \, \cos(2\pi U_2), \qquad Z_2 = \sqrt{-2 \ln U_1} \, \sin(2\pi U_2)\]

It avoids the inverse of \(\Phi\), which was once expensive. Libraries now use faster rejection methods, such as the ziggurat algorithm, for their built-in normal generator. The result is the same distribution.

Correlated normals#

For \(d\) assets with correlation matrix \(C\), write \(C = L L^\top\) with the Cholesky factor \(L\) and draw \(d\) independent normals \(Z\). Then \(L Z\) has the correlation \(C\). The matrix must be positive semi-definite. A matrix built from separately estimated correlations often is not, and the decomposition then fails or needs a repair, which is a model input to review. The tests and the repairs are in Numerical Linear Algebra.

Quasi-random numbers#

A quasi-random or low-discrepancy sequence, such as a Sobol sequence, is not random at all. It is built to fill the unit cube evenly, so that no region is left empty and no region is crowded. For a smooth integrand the error of the average falls close to \(1/N\), against \(1/\sqrt{N}\) for pseudo-random numbers. Monte Carlo, Part 3: Variance Reduction & Quasi-Monte Carlo shows this on option prices, and the dimension effects that limit it.

Worked example#

The example draws a million normals by inverse transform, by Box-Muller and from the library, and compares their moments, tail frequency and the Kolmogorov-Smirnov distance to the normal distribution function. It then checks reproducibility and the Cholesky construction, and compares the discrepancy and the integration error of pseudo-random and Sobol points.

Python code
"""Normal random numbers by inverse transform and Box-Muller, tests of them, correlation, and quasi-random points."""
import time

import numpy as np
from scipy.stats import kstest, norm, qmc


def inverse_transform(u):
    """Normal draws from uniforms: apply the inverse of the normal distribution function."""
    return norm.ppf(u)


def box_muller(u1, u2):
    """Two independent normals from two independent uniforms."""
    radius = np.sqrt(-2.0 * np.log(u1))
    return radius * np.cos(2.0 * np.pi * u2), radius * np.sin(2.0 * np.pi * u2)


def describe(name, z):
    tail = np.mean(z < -3.0)
    print(f"{name:<18} mean {z.mean():+.4f}  sd {z.std():.4f}  skew {np.mean(z**3):+.4f}  "
          f"kurt {np.mean(z**4):.4f}  P(z<-3) {tail:.5f}  KS {kstest(z, 'norm').statistic:.5f}")


if __name__ == "__main__":
    n = 1_000_000
    rng = np.random.default_rng(12345)
    u = rng.random(n)
    start = time.perf_counter()
    z_inv = inverse_transform(u)
    t_inv = time.perf_counter() - start
    start = time.perf_counter()
    a, b = box_muller(rng.random(n // 2), rng.random(n // 2))
    z_bm = np.concatenate([a, b])
    t_bm = time.perf_counter() - start
    z_gen = rng.standard_normal(n)

    print(f"{n:,} draws. Theory: mean 0, sd 1, skew 0, kurtosis 3, P(z<-3) {norm.cdf(-3):.5f}\n")
    describe("Inverse transform", z_inv)
    describe("Box-Muller", z_bm)
    describe("Library normal", z_gen)
    print(f"\nTime: inverse transform {t_inv * 1e3:.0f}ms, Box-Muller {t_bm * 1e3:.0f}ms")

    # The same seed gives the same numbers, which a valuation run needs to be reproducible.
    again = np.random.default_rng(12345).random(5)
    print(f"Same seed gives the same draws: {np.array_equal(again, u[:5])}")

    # Correlated normals: multiply independent normals by the Cholesky factor of the correlation matrix.
    rho = 0.7
    chol = np.linalg.cholesky(np.array([[1.0, rho], [rho, 1.0]]))
    pair = rng.standard_normal((n, 2)) @ chol.T
    print(f"Target correlation {rho}, sample correlation {np.corrcoef(pair.T)[0, 1]:.4f}")

    # Quasi-random points fill the unit square more evenly than pseudo-random ones: lower discrepancy.
    m = 1024
    sobol = qmc.Sobol(d=2, scramble=True, seed=7).random(m)
    pseudo = rng.random((m, 2))
    print(f"\nDiscrepancy of {m} points in 2D: pseudo-random {qmc.discrepancy(pseudo):.2e}, "
          f"Sobol {qmc.discrepancy(sobol):.2e}")

    # Integrating a smooth function: the mean of exp(x + y) over the unit square is exactly (e - 1)^2.
    exact = (np.e - 1) ** 2
    print(f"\nError in the mean of exp(x+y) over the unit square (exact {exact:.6f}):")
    print(f"{'Points':>8} {'Pseudo-random':>15} {'Sobol':>12}")
    for power in (6, 8, 10, 12, 14):
        m = 2**power
        err_p = abs(np.mean(np.exp(rng.random((m, 2)).sum(axis=1))) - exact)
        err_s = abs(np.mean(np.exp(qmc.Sobol(d=2, scramble=True, seed=power).random(m).sum(axis=1))) - exact)
        print(f"{m:>8} {err_p:15.2e} {err_s:12.2e}")

The output is:

1,000,000 draws. Theory: mean 0, sd 1, skew 0, kurtosis 3, P(z<-3) 0.00135

Inverse transform  mean -0.0003  sd 1.0002  skew +0.0030  kurt 3.0011  P(z<-3) 0.00134  KS 0.00090
Box-Muller         mean +0.0025  sd 1.0004  skew +0.0040  kurt 3.0096  P(z<-3) 0.00139  KS 0.00137
Library normal     mean -0.0011  sd 1.0014  skew -0.0042  kurt 3.0110  P(z<-3) 0.00135  KS 0.00121

Time: inverse transform 80ms, Box-Muller 43ms
Same seed gives the same draws: True
Target correlation 0.7, sample correlation 0.6999

Discrepancy of 1024 points in 2D: pseudo-random 2.73e-04, Sobol 7.68e-07

Error in the mean of exp(x+y) over the unit square (exact 2.952492):
  Points   Pseudo-random        Sobol
      64        2.29e-01     1.72e-03
     256        7.46e-02     3.51e-04
    1024        5.80e-02     2.15e-05
    4096        3.68e-03     1.66e-09
   16384        5.89e-04     8.12e-09

Reading the output:

  • The three normal generators agree. Their means, standard deviations and kurtosis are within the sampling error of a million draws, which is about 0.001 for the mean. The tail frequency below \(-3\) is 0.00134 to 0.00139 against the theoretical 0.00135.

  • The tail is the part to watch. A million draws put only about 1,350 points beyond \(-3\), so an option that depends on the tail uses very few of them. This is the problem that importance sampling addresses in Monte Carlo, Part 3: Variance Reduction & Quasi-Monte Carlo.

  • The same seed gives the same draws, and the Cholesky construction reproduces the correlation of 0.7 to 0.6999.

  • Sobol points are far more even. The discrepancy of 1,024 Sobol points is about 350 times below that of pseudo-random points. For the smooth integrand, the Sobol error at 4,096 points is 1.7e-09, against 3.7e-03.

  • Timings are indicative. They depend on the machine and on the load.

A valuation control view#

  • Fix and record the seed, the generator and its version: a Monte Carlo price that cannot be repeated cannot be reviewed. A change of library version can change the numbers, and with them the price, without any change in the model.

  • Separate numerical noise from model difference: when the independent price of a trade differs from the desk’s, first use the same numbers and the same transformation. If the difference vanishes, it was noise, and its size is the standard error. If it remains, it is the model or the implementation. See Monte Carlo, Part 1: Basic Pricing.

  • Test the generator’s output on the quantities that matter: the mean, the variance and the tail frequency of the draws that a trade uses, and the correlation matrix of the draws against the model input.

  • Check the correlation matrix: that it is positive semi-definite, and what repair was applied when it was not. A repair changes the correlation that the model uses, and so the price of a correlation-dependent product.

  • Quasi-random sequences need their settings recorded too: the scrambling, the number of points (often a power of two) and the order of the dimensions all change the answer.

Next, Stochastic Processes sets out the processes that these random numbers drive.