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 with an average. It can improve on typical Monte Carlo error under suitable conditions, but does not offer an rate for every function or dimension.
The star discrepancy of points is
It measures the worst difference between proportion and volume of a box anchored at the origin. Other discrepancies, such as a centered 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.
The Koksma-Hlawka inequality states for finite Hardy-Krause variation. In one dimension and for absolutely continuous , write . Integrating by parts,
The bound is deterministic and often conservative; 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 : the first eight values are . Halton combines reversals in distinct prime bases. In high dimensions those bases are large and initial projections can show structure.
Sobol digital nets use binary direction numbers and XOR operations. With Gray code , each coordinate is the XOR of direction numbers associated with active bits, scaled by . A net has controlled occupancy of dyadic boxes of volume ; only if is there exactly one point in each elementary box of volume . 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 . The generating vector and its coprimality with matter. Component-by-component (CBC) construction chooses each coordinate by a criterion; the example uses centered 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 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.
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 and divides variance into contributions . Truncation effective dimension is the smallest for which terms indexed only by 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 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.
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 .
"""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')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.
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, , , and . 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.
"""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
Step 1 of 3. How is integration error written?
import numpy as np
def sobol_points(n,d,direction_numbers):
pass