Module contents
Lesson 14 of 27Advanced 110 min

Advanced Monte Carlo II: quasi-Monte Carlo

Study low-discrepancy sequences and randomized quasi-Monte Carlo, from Koksma-Hlawka and digital nets to effective dimension and Brownian bridges.

After this lesson you can

  • Define star discrepancy and state and interpret the Koksma-Hlawka inequality.
  • Construct van der Corput, Halton and Sobol sequences and a rank-one lattice rule.
  • Apply randomized QMC with random shifts and Owen scrambling to obtain unbiased estimates with confidence intervals.
  • Explain high-dimensional QMC using ANOVA and effective dimension and improve ordering with Brownian bridge or PCA.
  • Use scipy.stats.qmc and compare MC, QMC and RQMC rates empirically.

Before you start

Covering the space

Independent Monte Carlo leaves gaps and clusters. Quasi-Monte Carlo (QMC) uses points constructed to cover the cube regularly and estimates ∫[0,1]df(x) dx\int_{[0,1]^d} f(x)\,\mathrm dx with an average. It can improve on typical Monte Carlo error N−1/2N^{-1/2} under suitable conditions, but does not offer an 1/N1/N rate for every function or dimension.

The star discrepancy of points x1,…,xNx_1,\ldots,x_N is

DN∗=sup⁡t∈[0,1]d∣1N∑i=1N1{xi∈[0,t)}−∏j=1dtj∣.D_N^*=\sup_{t\in[0,1]^d} \left|\frac1N\sum_{i=1}^N\mathbf1\{x_i\in[0,t)\} -\prod_{j=1}^d t_j\right|.

It measures the worst difference between proportion and volume of a box anchored at the origin. Other discrepancies, such as a centered L2L^2 version, average differences instead of taking that supremum and are not interchangeable. The box in the figure shows a local difference; it does not calculate the supremum.

InteractivePoints and anchored boxes

One box difference is not the full star discrepancy: that is the supremum over all anchored boxes. In the first two dimensions used here, the Sobol net of 2ᵐ points has one point in each elementary dyadic box of area 2⁻ᵐ.

Sequence
64
0.50
0.50
Points inside16
Proportion minus area0.0000
N a power of twoyes
Compare point prefixes and move the sides of a box; the observed proportion is compared with its area.

The Koksma-Hlawka inequality states ∣I^−I∣≤VHK(f)DN∗|\widehat I-I|\le V_{\rm HK}(f)D_N^* for finite Hardy-Krause variation. In one dimension and for absolutely continuous ff, write FN(t)=N−1∑i1{xi<t}F_N(t)=N^{-1}\sum_i\mathbf1\{x_i<t\}. Integrating by parts,

I^−I=∫01f′(t) [t−FN(t)] dt,∣I^−I∣≤DN∗∫01∣f′(t)∣ dt.\widehat I-I=\int_0^1 f'(t)\,[t-F_N(t)]\,\mathrm dt,\qquad |\widehat I-I|\le D_N^*\int_0^1|f'(t)|\,\mathrm dt.

The bound is deterministic and often conservative; VHKV_{\rm HK} can be enormous or infinite. It does not automatically become a probabilistic interval and does not apply without its variation assumptions.

Digital constructions and lattices

A low-discrepancy sequence can be constructed by reversing digits. Base-two van der Corput reverses the bits of 0,1,2,…0,1,2,\ldots: the first eight values are 0,1/2,1/4,3/4,1/8,5/8,3/8,7/80,1/2,1/4,3/4,1/8,5/8,3/8,7/8. Halton combines reversals in distinct prime bases. In high dimensions those bases are large and initial projections can show structure.

InteractiveHalton projections

Halton uses different prime bases. Scrambling can improve particular projections, but an image does not prove independence or remove all high-dimensional structure.

28
29
Scrambling
Dimensions28, 29
Two dimensions of a 40-dimensional sequence; scrambling is one fixed realization and does not guarantee absence of correlations.

Sobol digital nets use binary direction numbers and XOR operations. With Gray code g(i)=i⊕(i ⁣≫ ⁣1)g(i)=i\oplus(i\!\gg\!1), each coordinate is the XOR of direction numbers associated with active bits, scaled by 2−B2^{-B}. A net (t,m,d)(t,m,d) has controlled occupancy of dyadic boxes of volume 2t−m2^{t-m}; only if t=0t=0 is there exactly one point in each elementary box of volume 2−m2^{-m}. The figure’s property holds for the first two dimensions and directions used, not every projection or sequence. Direction tables matter for quality projections; Joe and Kuo describe their construction.

A rank-one lattice rule takes xi=(iz/N+Δ) mod 1x_i=(iz/N+\Delta)\bmod1. The generating vector and its coprimality with NN matter. Component-by-component (CBC) construction chooses each coordinate by a criterion; the example uses centered L2L^2 discrepancy on a small lattice and does not claim to optimize every integrand. For nonperiodic problems one can periodize the integrand or use suitable transforms, but must include the Jacobian and monitor regularity.

Randomizing to estimate uncertainty

Randomized QMC preserves structure and makes each point marginally uniform using a random shift or suitable digital scrambling. Estimates from independent randomized replicates allow a standard error across replicates; do not treat points within one net as IID. Owen nested scrambling uses independent permutations conditioned on digit prefixes; a triangular binary matrix plus digital shift is another randomization. SciPy Sobol uses LMS plus shift, not full nested scrambling.

For sufficiently smooth nets and functions, RMSE bounds of order N−3/2N^{-3/2} are known with logarithmic factors and other assumptions; this is no promise for discontinuous indicators or every realization. Implementations use finitely many bits: the lab adds uniform noise below the last bit in its custom scramblings to recover continuous marginals, while SciPy operates at finite precision.

InteractiveObserved integration errors
  • MC RMSE
  • Sobol error
  • Randomized Sobol RMSE

Axes: log₂ N and log₁₀ error, with floor 10⁻¹⁵. The two-variable integrand ignores the rest; the indicator is discontinuous. One curve or 16 replicates do not establish a universal rate.

Dimension
Integrand
Deterministic Sobol error is one realization; MC and RQMC curves are RMSE over 16 replicates against known integrals.

Powers of two preserve the net guarantees of a complete Sobol block. Taking 1000 instead of 1024 or discarding the first point can lose those properties, but does not mean actual error at 1000 is always greater: it depends on the integrand. For normals, the first unrandomized point contains zeros and the inverse transform is infinite; that endpoint should not be hidden. The lab uses scrambling and clips inputs to machine precision before applying the normal inverse.

Effective dimension and paths

An orthogonal ANOVA decomposition writes f=∑u⊆{1,…,d}fuf=\sum_{u\subseteq\{1,\ldots,d\}} f_u and divides variance into contributions σu2\sigma_u^2. Truncation effective dimension is the smallest ss for which terms indexed only by {1,…,s}\{1,\ldots,s\} explain a chosen fraction of variance. Superposition effective dimension limits the number of interacting variables, not their indices. Both depend on integrand, distribution and threshold; changing variable order changes the first.

In discretized Brownian motion, sequential order uses one normal coordinate per increment. The bridge first determines W(T)W(T) and then conditional midpoints; it places large-scale variation in early coordinates. PCA uses covariance eigenvectors to concentrate total path variance in linearly optimal order. Neither measure guarantees that an option payoff has the same effective dimension.

InteractiveBrownian construction order
  • Partial
  • Complete

Unrevealed coordinates are set to zero, so the partial curve is the conditional mean in this Gaussian representation. The variance shown sums variances over 64 times; it is not automatically the effective dimension of an option payoff.

Construction
1
Fraction of path variance3.08 %
Unrevealed coordinates are set to zero. The fraction shown is path variance, not payoff ANOVA variance.

In our 64-time example, the first coordinate explains 67.19% of summed path variances with a bridge and 3.08% with increments. These are transformation-matrix calculations; the figure’s two curves use the same normal coordinates but represent different constructions.

Lab: construct and compare

The first cell implements digit reversals, Sobol in three dimensions with explicit directions, two scramblings, a CBC lattice and a Brownian bridge. The CBC lattice minimizes centered discrepancy by exhaustive search, so it is reserved for small NN.

[ ]QMC constructions from scratchBrowser
"""Construcciones elementales QMC y puente browniano."""
import numpy as np
from math import gcd

def van_der_corput(n,base=2):
    if n<0 or base<2:raise ValueError('n o base inválidos')
    out=np.zeros(n)
    for i in range(n):
        k=i;factor=1/base
        while k:out[i]+=(k%base)*factor;k//=base;factor/=base
    return out

def primes(d):
    out=[];x=2
    while len(out)<d:
        if all(x%p for p in out if p*p<=x):out.append(x)
        x+=1
    return out

def halton(n,d):
    return np.column_stack([van_der_corput(n,b) for b in primes(d)])

def star_discrepancy_1d(points):
    x=np.sort(np.asarray(points,dtype=float).ravel());n=len(x)
    if n==0 or np.any((x<0)|(x>=1)):raise ValueError('puntos en [0,1)')
    return float(max(np.max(np.arange(1,n+1)/n-x),np.max(x-np.arange(n)/n)))

def directions_three(bits=30):
    """Primeras tres dimensiones: recurrencias de direcciones binarias."""
    if bits<2 or bits>52:raise ValueError('bits fuera de rango')
    v=np.zeros((3,bits),dtype=np.uint64)
    for j in range(bits):v[0,j]=np.uint64(1) << np.uint64(bits-1-j)
    v[1,0]=np.uint64(1) << np.uint64(bits-1)
    for j in range(1,bits):v[1,j]=v[1,j-1]^(v[1,j-1]>>np.uint64(1))
    v[2,0]=np.uint64(1) << np.uint64(bits-1);v[2,1]=np.uint64(3) << np.uint64(bits-2)
    for j in range(2,bits):v[2,j]=v[2,j-2]^(v[2,j-2]>>np.uint64(2))^v[2,j-1]
    return v

def sobol_points(n,d,direction_numbers):
    """Gray i xor (i>>1); direction_numbers tiene forma (d,bits)."""
    v=np.asarray(direction_numbers,dtype=np.uint64);bits=v.shape[1]
    if n<0 or d<1 or d>v.shape[0] or bits>52 or n>2**bits:raise ValueError('dimensión o longitud inválida')
    out=np.zeros((n,d),dtype=np.uint64)
    for i in range(n):
        gray=i^(i>>1);bit=0
        while gray:
            if gray&1:out[i]^=v[:d,bit]
            gray>>=1;bit+=1
    return out.astype(float)/(2**bits)

def digital_scramble(points,bits,rng):
    """Matriz binaria triangular, desplazamiento digital y ruido bajo el último bit."""
    p=np.asarray(points);n,d=p.shape;integers=np.rint(p*2**bits).astype(np.uint64)
    out=np.zeros_like(integers)
    for dim in range(d):
        masks=rng.integers(0,2,(bits,bits));shift=rng.integers(0,2,bits)
        for i in range(bits):
            value=((integers[:,dim]>>np.uint64(bits-1-i))&1).copy()
            for j in range(i):value^=((integers[:,dim]>>np.uint64(bits-1-j))&1)*np.uint64(masks[i,j])
            value^=np.uint64(shift[i]);out[:,dim]|=value<<np.uint64(bits-1-i)
    return (out.astype(float)+rng.random((n,d)))/2**bits

def nested_owen_scramble(points,bits,rng):
    """Permutaciones binarias independientes por prefijo y dígitos residuales."""
    p=np.asarray(points);n,d=p.shape;integers=np.rint(p*2**bits).astype(np.uint64)
    out=np.zeros_like(integers)
    for dim in range(d):
        permutations={}
        for row in range(n):
            prefix=0;value=0
            for level in range(bits):
                original=int((integers[row,dim]>>np.uint64(bits-1-level))&np.uint64(1))
                key=(level,prefix)
                if key not in permutations:permutations[key]=int(rng.integers(0,2))
                value=(value<<1)|(original^permutations[key])
                prefix=(prefix<<1)|original
            out[row,dim]=value
    return (out.astype(float)+rng.random((n,d)))/2**bits

def lattice(n,z,shift=None):
    z=np.asarray(z,dtype=int)
    if n<2 or any(gcd(int(a),n)!=1 for a in z):raise ValueError('componentes coprimas con n')
    shift=np.zeros(len(z)) if shift is None else np.asarray(shift)
    return (np.arange(n)[:,None]*z[None,:]/n+shift)%1

def centered_discrepancy_sq(points):
    x=np.asarray(points);n,d=x.shape;a=np.abs(x-.5)
    one=np.prod(1+.5*a-.5*a*a,axis=1).mean()
    pair=np.prod(1+.5*a[:,None,:]+.5*a[None,:,:]-.5*np.abs(x[:,None,:]-x[None,:,:]),axis=2).mean()
    return float((13/12)**d-2*one+pair)

def lattice_cbc(n,d):
    """CBC exhaustivo para discrepancia L2 centrada, destinado a mallas pequeñas."""
    if n<2 or d<1:raise ValueError('parámetros inválidos')
    choices=[z for z in range(1,n) if gcd(z,n)==1];z=[1]
    for _ in range(1,d):
        candidate=min(choices,key=lambda a:centered_discrepancy_sq(lattice(n,z+[a])))
        z.append(candidate)
    return np.array(z)

def brownian_paths(z,T=1.,bridge=True):
    """z (réplicas, potencia de dos) -> W(t1),...,W(T)."""
    z=np.asarray(z,dtype=float);batch,n=z.shape
    if n<1 or (n&(n-1)) or T<=0:raise ValueError('n potencia de dos y T positivo')
    if not bridge:return np.cumsum(z*np.sqrt(T/n),axis=1)
    W=np.zeros((batch,n+1));W[:,-1]=np.sqrt(T)*z[:,0];queue=[(0,n)];k=1
    while queue:
        left,right=queue.pop(0)
        if right-left<=1:continue
        mid=(left+right)//2;wl=(right-mid)/(right-left);wr=(mid-left)/(right-left)
        sd=np.sqrt(T/n*(mid-left)*(right-mid)/(right-left))
        W[:,mid]=wl*W[:,left]+wr*W[:,right]+sd*z[:,k];k+=1
        queue.extend([(left,mid),(mid,right)])
    return W[:,1:]
print('QMC listo')
[ ]Comparison with SciPy and boxesBrowser
from scipy.stats import qmc as scipy_qmc
v=directions_three();points=sobol_points(1024,3,v)
reference=scipy_qmc.Sobol(3,scramble=False,bits=30).random_base2(10)
print('primeros ocho van der Corput',van_der_corput(8))
print('discrepancia estrella de cuatro',star_discrepancy_1d(van_der_corput(4)))
print('diferencia máxima Sobol respecto a SciPy',np.max(np.abs(points-reference)))
print('diferencia máxima Halton respecto a SciPy',np.max(np.abs(halton(128,3)-scipy_qmc.Halton(3,scramble=False).random(128))))
for k in range(9):
    ix=np.floor(points[:256,0]*2**k).astype(int)
    iy=np.floor(points[:256,1]*2**(8-k)).astype(int)
    assert np.all(np.bincount(ix+2**k*iy,minlength=256)==1)
print('cajas diádicas 2D: comprobadas')
z=lattice_cbc(32,3);lat=lattice(32,z)
print('retículo CBC',z,'discrepancia propia/SciPy',centered_discrepancy_sq(lat),scipy_qmc.discrepancy(lat))
rng=np.random.default_rng(42)
for name,method in [('LMS+shift',digital_scramble),('Owen anidado',nested_owen_scramble)]:
    s=method(points[:256],30,rng)
    print(name,'rango',s.min(),s.max(),'promedio',s.mean(axis=0))

For an uncertainty interval, independent replicates of nets are generated. The example gives mean and standard error across replicates; with only 16, the normal interval is approximate and may be unreliable.

[ ]Randomized QMC replicatesBrowser
from scipy.stats import t as student_t
truth=(1-np.exp(-1))**3;means=[]
base=sobol_points(256,3,directions_three())
for seed in range(16):
    pts=nested_owen_scramble(base,30,np.random.default_rng(seed))
    means.append(np.exp(-pts.sum(axis=1)).mean())
means=np.array(means);se=means.std(ddof=1)/np.sqrt(len(means))
print('integral exacta',truth,'media RQMC',means.mean(),'SE',se)
print('intervalo t aproximado 95 %',means.mean()+np.array([-1,1])*student_t.ppf(.975,15)*se)

Run “QMC constructions from scratch” first in the same session. The final comparison uses a 64-date arithmetic Asian call, S0=K=100S_0=K=100, r=0.03r=0.03, σ=0.2\sigma=0.2 and T=1T=1. Each replicate uses 512 paths; bridge and sequential order receive the same randomized Sobol points within each replicate. Deviations across twelve replicates measure estimator variability for this model, not an asymptotic rate.

[ ]Brownian bridge and Asian optionBrowser
"""RQMC y opción asiática: réplicas independientes y puente browniano."""
import numpy as np
from scipy.special import ndtri
from scipy.stats import qmc

def asian_qmc(n=512,replicas=12,steps=64):
    """Resultados por réplica para mismo modelo GBM bajo orden secuencial/puente."""
    if n<2 or (n&(n-1)) or replicas<2:raise ValueError('n potencia de dos y al menos dos réplicas')
    out={'mc':[],'sequential':[],'bridge':[]};T=1.;r=.03;sigma=.2
    for seed in range(replicas):
        rng=np.random.default_rng(1000+seed);u_mc=rng.random((n,steps))
        sob=qmc.Sobol(steps,scramble=True,seed=2000+seed).random_base2(int(np.log2(n)))
        for name,u,bridge in [('mc',u_mc,False),('sequential',sob,False),('bridge',sob,True)]:
            z=ndtri(np.clip(u,np.finfo(float).eps,1-np.finfo(float).eps))
            W=brownian_paths(z,T,bridge);t=np.arange(1,steps+1)*T/steps
            path=100*np.exp((r-sigma*sigma/2)*t+sigma*W)
            payoff=np.exp(-r*T)*np.maximum(path.mean(axis=1)-100,0)
            out[name].append(float(payoff.mean()))
    return out

def convergence_experiment(d,kind,m=8,replicas=16,seed=42):
    """Error absoluto QMC, RMSE MC y RQMC; valor exacto conocido."""
    n=2**m
    if kind=='effective':
        def f(x):return np.exp(-np.sum(x[:,:2],axis=1)/2)
        truth=(2*(1-np.exp(-.5)))**2
    elif kind=='smooth':
        def f(x):return np.exp(-np.sum(x,axis=1)/d)
        truth=(d*(1-np.exp(-1/d)))**d
    elif kind=='indicator':
        def f(x):return (np.sum(x,axis=1)<d/2).astype(float)
        truth=.5
    else:raise ValueError('tipo desconocido')
    det=qmc.Sobol(d,scramble=False).random_base2(m)
    Q=float(abs(f(det).mean()-truth));mc=[];rq=[]
    for j in range(replicas):
        x=np.random.default_rng(seed+j).random((n,d))
        s=qmc.Sobol(d,scramble=True,seed=seed+j).random_base2(m)
        mc.append(float(f(x).mean()));rq.append(float(f(s).mean()))
    return Q,float(np.sqrt(np.mean((np.array(mc)-truth)**2))),float(np.sqrt(np.mean((np.array(rq)-truth)**2)))
if __name__=='__main__':
    result=asian_qmc()
    for name,v in result.items():
        print(name,'media',np.mean(v),'desviación entre réplicas',np.std(v,ddof=1),'SE de la media',np.std(v,ddof=1)/np.sqrt(len(v)))

Exercises

NumericEighth point
Counting the first point as i=0, what is the eighth base-two van der Corput value?
NumericDiscrepancy of four points
What is the 1D star discrepancy of the first four points 0, 1/2, 1/4 and 3/4?
ProofKoksma-Hlawka in 1D
Prove: Obtain the bound by integration by parts.
0
f is absolutely continuous and Fₙ is the empirical CDF of the points.

Step 1 of 3. How is integration error written?

QuizSobol size
What can be said about using 1000 Sobol points instead of 1024?
NumericEffective dimension
An additive ten-variable integrand has variance contributions 0.40, 0.25, 0.15, 0.10, 0.06, 0.02, 0.01, 0.005, 0.003, 0.002. What is the truncation effective dimension at 99% in that order?
CodeSobol with Gray code
Implement sobol_points(n,d,direction_numbers). The uint64 table has shape (dimensions,bits) and encodes B-bit integers. For each index use i XOR (i>>1), combine active-bit directions and divide by 2^B.
import numpy as np
def sobol_points(n,d,direction_numbers):
  pass
Shift+Enter to run
Key idea
Low discrepancy organizes points; independent randomization measures variability, and effective dimension explains when that organization can help.