Module contents
Lesson 13 of 27Core 110 min

Advanced Monte Carlo I: variance reduction

Monte Carlo error is σ/√N, so reducing it tenfold requires a hundredfold increase in computation unless σ is reduced. Build classical variance-reduction methods and apply them to rare-event simulation, accounting for their assumptions, bias and cost.

After this lesson you can

  • Prove when antithetic variates reduce variance and measure the efficiency gain in variance per cost.
  • Derive the optimal control-variate coefficient and its regression relationship, extending it to multiple controls.
  • Implement stratified sampling with proportional and Neyman allocation, and Latin hypercube sampling.
  • Apply conditional Monte Carlo when part of a problem admits an analytic solution.
  • Design rare-event importance proposals using exponential tilting and cross-entropy, and diagnose infinite variance.

Before you start

Accuracy per unit of work

For independent samples with finite variance, the standard error of a mean is σ/N\sigma/\sqrt N. Reducing it tenfold requires one hundred times as many samples if everything else stays equal. Estimator efficiency combines variance and cost: for a fixed budget, compare approximately Var⁡(μ^)×coste\operatorname{Var}(\widehat\mu)\times\text{coste}. Include pilots, generation, evaluation and wall time when they affect the decision. Variance does not measure bias or by itself detect an importance proposal that fails to cover the event.

InteractiveEstimator race

From top to bottom: Naive: σ 0.14599Antithetic: σ 0.04956Control: σ 0.034632D strata: σ 0.02111Latin hypercube: σ 0.03073

Bands are mean ±1.96 standard deviations of 200 estimates, not confidence intervals calculated from individual samples. Each method uses the same number of integrand evaluations; additional pilot and sorting costs are excluded and should count in a time comparison.

2D integrand
0
Evaluations per replicate64
Reference integral2.95249
Pilot coefficient2.9153
Each band is mean ±1.96 standard deviations across 200 independent replicates, with equal numbers of integrand evaluations. Pilot and sorting costs are excluded.

The functions are ex+ye^{x+y}, (x−1/2)2+(y−1/2)2(x-1/2)^2+(y-1/2)^2 and a localized Gaussian peak, on the unit square. We evaluate 200 independent replicates per method and budget. The control uses C=x+yC=x+y with mean one, with coefficient estimated in an independent 5000-point pilot; stratification divides each axis into the same number of intervals. Bands show empirical dispersion and do not guarantee 95% coverage for a skewed distribution. Latin hypercube and strata include additional operations; the plotted budget counts function calls, not measured time.

Pairs and controls

Antithetic variates pair f(U)f(U) and f(1−U)f(1-U). If ff is increasing, f(1−U)f(1-U) is decreasing and their covariance is nonpositive: using an independent copy VV,

2Cov⁡(f(U),f(1−U))=E[(f(U)−f(V))(f(1−U)−f(1−V))]≤0.2\operatorname{Cov}(f(U),f(1-U)) =\mathbb E[(f(U)-f(V))(f(1-U)-f(1-V))]\le0.

At the same cost of two evaluations, the pair average has variance no greater than the average of two independent samples. For f(u)=(u−1/2)2f(u)=(u-1/2)^2, however, f(U)=f(1−U)f(U)=f(1-U): the two evaluations are identical and the average’s variance doubles relative to two independent ones. Monotonicity, correlation and cost matter.

For a control variate CC with known mean μC\mu_C, use Z=Y−β(C−μC)Z=Y-\beta(C-\mu_C). Its expectation matches that of YY if β\beta is fixed, and

β∗=Cov⁡(Y,C)Var⁡(C),Var⁡(Z∗)=Var⁡(Y)(1−ρ2).\beta_*=\frac{\operatorname{Cov}(Y,C)}{\operatorname{Var}(C)},\qquad \operatorname{Var}(Z_*)=\operatorname{Var}(Y)(1-\rho^2).

The optimum is the regression slope with an intercept. For multiple controls solve ΣCCβ=Cov⁡(C,Y)\Sigma_{CC}\beta=\operatorname{Cov}(C,Y) if the matrix is invertible; redundant controls require regularization or dimension reduction. Estimating β\beta with the same data can introduce finite-sample bias. An independent pilot or cross-fitting can separate fitting from estimation; pilot cost counts.

InteractiveControl as regression

Fixed synthetic data: the parabola and slope are calculated from the same sample. In control-variate estimation, fitting β on the same sample can introduce bias; an independent pilot avoids that coupling.

0.00
Regression slope1.986
Residual / initial variance1.0000
Sample 1−ρ²0.1721
The cloud is fixed synthetic data; the parabola shows sample residual variance and its minimum coincides with the regression slope.

Strata, hypercubes and conditioning

Stratification divides space into regions with probabilities whw_h and estimates each mean. With independent samples within each stratum, variance is ∑hwh2σh2/nh\sum_h w_h^2\sigma_h^2/n_h. If costs are equal and σh\sigma_h is known, Neyman allocation nh∝whσhn_h\propto w_h\sigma_h minimizes this variance for a given total; proportional allocation uses nh∝whn_h\propto w_h. Unknown variances are estimated with a pilot and each stratum needs enough samples. With different costs the optimal allocation changes.

Latin hypercube sampling places one observation in each interval of each marginal and permutes coordinates. It often helps when low-dimensional additive effects dominate; interactions may reduce the gain. Points within a design are not independent, so the naive IID standard error is invalid. Repeat randomized designs independently and calculate uncertainty across their estimates.

Conditional Monte Carlo replaces YY with E[Y∣X]\mathbb E[Y\mid X]. The law of total variance ensures Var⁡(E[Y∣X])≤Var⁡(Y)\operatorname{Var}(\mathbb E[Y\mid X])\le\operatorname{Var}(Y) provided the second moment exists. Gain per unit time also depends on the cost of computing that expectation. For independent normal X,YX,Y and event X+Y>aX+Y>a, conditioning on XX replaces the indicator with Φ(X−a)\Phi(X-a).

Importance sampling and rare events

Importance sampling generates Xi∼qX_i\sim q and estimates Ep[f(X)]\mathbb E_p[f(X)] with 1N∑f(Xi)p(Xi)/q(Xi)\frac1N\sum f(X_i)p(X_i)/q(X_i). It needs q>0q>0 wherever fpfp is nonzero, and a finite second moment for usual intervals. For an indicator, the ideal proposal q∗=p(x)1A(x)/P(A)q_*=p(x)\mathbf1_A(x)/P(A) would give zero variance, but depends on the unknown probability. Gaussian tilting toward the tail is a practical approximation.

InteractiveTilting a normal tail
  • Target N(0,1)
  • Proposal
  • Threshold a=5

The 1200 base normals are fixed. Relative variance is per sample and is obtained by quadrature of the second moment over a finite tail; for σ² < 1/2 it is infinite. Sample ESS can look reassuring even when extreme weights have not been observed.

5.0
1.00
Exact probability2.8665e-7
Weight ESS, 1200 samples3.5
Event contribution ESS173.6
Hits under proposal569
Relative variance per sample5.68e+0
The target density is N(0,1) and the event is X>5. Weight ESS and event-contribution ESS answer different questions.

A narrow proposal can have infinite variance despite producing an apparently stable sample. For p=N(0,1)p=N(0,1), q=N(μ,σ2)q=N(\mu,\sigma^2) and event X>5X>5, σ2<1/2\sigma^2<1/2 makes the estimator’s second moment diverge. In the boundary case σ2=1/2\sigma^2=1/2 the mean and tail also matter; we do not generalize the strict inequality to the boundary. Weight ESS does not guarantee finite variance or automatically measure tail accuracy. In the figure the finite second moment is numerically integrated over a truncated region; divergence is determined analytically.

Cross-entropy approximates the event’s conditional distribution within a chosen family. When initial events are insufficient, intermediate quantile levels gradually move the proposal closer; elites are weighted by p/qp/q. Fitting and the final sample are independent in the lab. The method depends on family, levels and support; it does not promise an error tolerance in every realization. Splitting and subset simulation are alternatives using successive survival levels, with their own dependencies and diagnostics. The review by Kroese, Rubinstein and Glynn develops these ideas.

Lab: reproducible tools

The following functions implement pairs, control, strata, hypercube, Asian option, Gaussian tilting and cross-entropy. Standard errors are calculated across independent units: pairs for antithetics, samples within each stratum, or complete-design replicates for the hypercube.

[ ]ToolboxBrowser
"""Estimadores de Monte Carlo, controles independientes y eventos raros."""
import numpy as np
from scipy.special import ndtr,ndtri

def antithetic(f,n,rng):
    """n pares: devuelve media, error estándar entre pares y coste 2n."""
    if n<2:raise ValueError('se necesitan al menos dos pares')
    u=rng.random(n);z=(f(u)+f(1-u))/2
    return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),2*n

def control_estimate(y,c,mu_c,beta):
    """beta fijado antes de obtener (y,c); sin sesgo si mu_c es exacta."""
    z=np.asarray(y)-beta*(np.asarray(c)-mu_c)
    return float(z.mean()),float(z.std(ddof=1)/np.sqrt(len(z)))

def stratified(f,n_per,rng):
    """Estratos de igual tamaño con n_per muestras independientes en cada uno."""
    if len(n_per)<1 or np.any(np.asarray(n_per)<2):raise ValueError('se requieren al menos dos muestras por estrato')
    k=len(n_per);values=[f((i+rng.random(int(n)))/k) for i,n in enumerate(n_per)]
    estimate=np.mean([v.mean() for v in values])
    se=np.sqrt(sum(v.var(ddof=1)/len(v) for v in values))/k
    return float(estimate),float(se)

def latin_hypercube(n,d,rng):
    return np.column_stack([(rng.permutation(n)+rng.random(n))/n for _ in range(d)])

def asian_pair(n,rng,S0=100.,K=100.,r=.03,sigma=.2,T=1.,m=12):
    dt=T/m;Z=rng.standard_normal((n,m))
    logS=np.log(S0)+np.cumsum((r-sigma**2/2)*dt+sigma*np.sqrt(dt)*Z,axis=1)
    paths=np.exp(logS);discount=np.exp(-r*T)
    return discount*np.maximum(paths.mean(axis=1)-K,0),discount*np.maximum(np.exp(logS.mean(axis=1))-K,0)

def asian_geometric_price(S0=100.,K=100.,r=.03,sigma=.2,T=1.,m=12):
    mean=np.log(S0)+(r-sigma**2/2)*T*(m+1)/(2*m)
    var=sigma**2*T*(m+1)*(2*m+1)/(6*m*m);sd=np.sqrt(var)
    d2=(mean-np.log(K))/sd;d1=d2+sd
    return np.exp(-r*T)*(np.exp(mean+var/2)*ndtr(d1)-K*ndtr(d2))

def gaussian_tail(a,n,rng,mu=None,sigma=1.):
    """IS ordinario no autonormalizado; pesos y contribuciones para diagnóstico."""
    if mu is None:mu=a
    x=rng.normal(mu,sigma,n)
    logw=np.log(sigma)-.5*x*x+.5*((x-mu)/sigma)**2
    z=np.exp(logw)*(x>a);w=np.exp(logw)
    return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),float(w.sum()**2/np.sum(w*w)),z

def cross_entropy_is(log_target_indicator,family,n_iter,rho):
    """Ajuste de media gaussiana en covarianza identidad para un score creciente.

    log_target_indicator(x) devuelve (score, log_indicador), con cero en el
    evento final y -inf fuera. family contiene mean, n, rng y threshold.
    Los umbrales intermedios usan cuantiles; las élites se ponderan p/q.
    Se devuelve una propuesta; la estimación usa una muestra independiente.
    """
    mean=np.array(family['mean'],dtype=float);n=int(family['n']);rng=family['rng'];threshold=float(family['threshold'])
    if n<10 or not 0<rho<1 or n_iter<1:raise ValueError('parámetros inválidos')
    history=[]
    for _ in range(n_iter):
        x=rng.normal(size=(n,len(mean)))+mean
        score,log_indicator=log_target_indicator(x)
        level=min(threshold,float(np.quantile(score,1-rho)))
        elite=(score>=level)
        if level>=threshold:elite &= np.isfinite(log_indicator)
        logw=-x@mean+.5*(mean@mean)
        lw=logw[elite];w=np.exp(lw-lw.max())
        mean=np.sum(x[elite]*w[:,None],axis=0)/w.sum()
        history.append((level,mean.copy()))
    return mean,history

def tandem_score(x):
    """Máximo tiempo total de un trabajo en dos servidores FIFO."""
    arrival=np.cumsum(x[:,:,0],axis=1);end1=np.zeros(len(x));end2=np.zeros(len(x));largest=np.zeros(len(x))
    for j in range(x.shape[1]):
        end1=np.maximum(arrival[:,j],end1)+x[:,j,1]
        end2=np.maximum(end1,end2)+x[:,j,2]
        largest=np.maximum(largest,end2-arrival[:,j])
    return largest

def tandem_occupancy(x):
    """Mayor número simultáneo en la red al llegar un trabajo."""
    arrival=np.cumsum(x[:,:,0],axis=1);end1=np.zeros(len(x));end2=np.zeros(len(x));departures=[]
    for j in range(x.shape[1]):
        end1=np.maximum(arrival[:,j],end1)+x[:,j,1]
        end2=np.maximum(end1,end2)+x[:,j,2];departures.append(end2.copy())
    departure=np.stack(departures,axis=1)
    return np.max(np.sum((arrival[:,None,:]<=arrival[:,:,None])&(departure[:,None,:]>arrival[:,:,None]),axis=2),axis=1)

def queue_ce(threshold=15.,jobs=10,n=4000,iterations=5,rho=.1,seed=42,score_fn=tandem_score):
    """Ajusta tasas exponenciales por élites ponderadas; muestra final independiente."""
    rng=np.random.default_rng(seed);target=np.array([1.,1.5,1.5]);rates=target.copy();history=[]
    for _ in range(iterations):
        x=rng.exponential(1/rates,size=(n,jobs,3));score=score_fn(x);level=min(threshold,float(np.quantile(score,1-rho)))
        elite=score>=level;logw=np.sum(np.log(target/rates)+(rates-target)*x,axis=(1,2))
        lw=logw[elite];w=np.exp(lw-lw.max());means=np.sum(x[elite]*w[:,None,None],axis=(0,1))/(jobs*w.sum())
        proposed=np.clip(1/means,.2*target,1.8*target);rates=.3*rates+.7*proposed
        history.append((level,rates.copy()))
    return target,rates,history

def queue_estimate(target,rates,threshold,n=20000,jobs=10,seed=123,score_fn=tandem_score):
    rng=np.random.default_rng(seed);x=rng.exponential(1/rates,size=(n,jobs,3))
    hit=score_fn(x)>=threshold
    logw=np.sum(np.log(target/rates)+(rates-target)*x,axis=(1,2))
    z=np.exp(logw)*hit
    return float(z.mean()),float(z.std(ddof=1)/np.sqrt(n)),int(hit.sum())
[ ]Antithetics, strata and hypercube replicateBrowser
rng=np.random.default_rng(42);f=lambda x:np.exp(x)
u=rng.random(2000);plain=(f(u).mean(),f(u).std(ddof=1)/np.sqrt(len(u)))
print('IID estimación y error estándar',plain)
print('antitético 1000 pares',antithetic(f,1000,rng))
print('estratos de igual peso',stratified(f,np.full(10,200),rng))
rep=np.array([np.exp(latin_hypercube(200,1,rng)[:,0]).mean() for _ in range(100)])
print('hipercubo 100 diseños: media y error estándar entre diseños',rep.mean(),rep.std(ddof=1)/np.sqrt(len(rep)))
print('integral exacta',np.e-1)

The first position in the figure is reproduced with 200 replicates of 64 evaluations per method and an independent pilot. The five estimates in each replicate use their own samples; pilot cost is separate.

[ ]One position in the raceBrowser
rng=np.random.default_rng(41);fun=lambda x:np.exp(x[:,0]+x[:,1])
pilot=rng.random((5000,2));v=fun(pilot);c=pilot.sum(axis=1)
beta=np.cov(v,c,ddof=1)[0,1]/np.var(c,ddof=1)
m=8;n=m*m;rep={key:[] for key in ('plain','anti','control','strat','lhs')}
for _ in range(200):
    x=rng.random((n,2));rep['plain'].append(fun(x).mean())
    rep['control'].append(np.mean(fun(x)-beta*(x.sum(axis=1)-1)))
    x=rng.random((n//2,2));rep['anti'].append(np.mean((fun(x)+fun(1-x))/2))
    x=np.array([(np.array([i,j])+rng.random(2))/m for i in range(m) for j in range(m)])
    rep['strat'].append(fun(x).mean())
    rep['lhs'].append(fun(latin_hypercube(n,2,rng)).mean())
for key,v in rep.items():print(key,'media',np.mean(v),'desviación entre réplicas',np.std(v,ddof=1))

The Asian option uses twelve observations of a geometric Brownian path, S0=K=100S_0=K=100, r=0.03r=0.03, σ=0.2\sigma=0.2, T=1T=1, with no dividends. The geometric mean of prices has a normal logarithm, so its option price is known; that price controls the arithmetic payoff. The pilot is discarded and does not contribute to the final sample.

[ ]Asian option and geometric controlBrowser
rng=np.random.default_rng(42);yp,cp=asian_pair(5000,rng)
beta=np.cov(yp,cp,ddof=1)[0,1]/np.var(cp,ddof=1)
y,c=asian_pair(20000,rng);known=asian_geometric_price()
controlled=y-beta*(c-known)
print('precio geométrico analítico',known,'beta piloto',beta)
print('aritmética IID, SE',y.mean(),y.std(ddof=1)/np.sqrt(len(y)))
print('control, SE',controlled.mean(),controlled.std(ddof=1)/np.sqrt(len(y)))
print('reducción de varianza observada',np.var(y,ddof=1)/np.var(controlled,ddof=1))
[ ]Conditional Monte CarloBrowser
rng=np.random.default_rng(123);x=rng.normal(size=20000);y=rng.normal(size=20000);a=3.
raw=(x+y>a).astype(float);conditional=ndtr(x-a)
print('directo',raw.mean(),'SE',raw.std(ddof=1)/np.sqrt(len(raw)))
print('condicional',conditional.mean(),'SE',conditional.std(ddof=1)/np.sqrt(len(raw)))
print('referencia normal',ndtr(-a/np.sqrt(2)))

A controlled cross-entropy test uses a normal tail of probability 10−810^{-8}. The proposal is fitted with pilot samples and estimated with 10000 subsequent samples; the normal reference allows this realization to be checked, but an error below 5% for one seed is not a probabilistic guarantee for every run.

[ ]Cross-entropy for a known tailBrowser
rng=np.random.default_rng(7);a=ndtri(1-1e-8)
target=lambda x:(x[:,0],np.where(x[:,0]>a,0.,-np.inf))
family={'mean':np.zeros(1),'n':3000,'rng':rng,'threshold':a}
mu,history=cross_entropy_is(target,family,5,.1)
estimate,se,ess,z=gaussian_tail(a,10000,rng,float(mu[0]))
print('niveles y medias',history)
print('estimación, SE, ESS pesos',estimate,se,ess,'error relativo',abs(estimate/1e-8-1))

The next synthetic network has ten jobs, exponential arrivals of rate one and two FIFO servers with exponential service of rate 1.5. The event is that some job spends at least 15 time units in the network. The algorithm adapts rates using elites and weights, then estimates with another seed. The proposal is limited to less than twice each original rate, a sufficient condition for a finite second moment of the full weight in this exponential model. The IID comparison uses 100000 replicates and may contain very few events.

[ ]Queueing network and adaptive importance samplingBrowser
target,rates,history=queue_ce()
print('tasas adaptadas',rates,'niveles',[h[0] for h in history])
print('IS: estimación, SE, eventos bajo propuesta',queue_estimate(target,rates,15.,n=20000))
print('IID: estimación, SE, eventos',queue_estimate(target,target,15.,n=100000))

As a different overflow criterion, consider a capacity of nine jobs across the network and count whether ten coexist. Occupancy can increase only on an arrival; compare the maximum with the threshold. This realization does not reach the final level during five fitting steps, but still uses the resulting proposal and independent samples to estimate the event; the proposal is not claimed to be optimal.

[ ]Network capacity overflowBrowser
target,rates,history=queue_ce(threshold=10,score_fn=tandem_occupancy)
print('tasas',rates,'niveles',[h[0] for h in history])
print('IS',queue_estimate(target,rates,10,n=20000,score_fn=tandem_occupancy))
print('IID',queue_estimate(target,target,10,n=20000,score_fn=tandem_occupancy))

For an illustrative reliability model, failure means Z>aZ>a with Z∼N(0,1)Z\sim N(0,1) and a=Φ−1(1−10−6)a=\Phi^{-1}(1-10^{-6}). It does not represent a real structure. Compare a tilted proposal with IID; if no IID failures occur, a zero result does not prove zero probability.

[ ]Idealized structural failureBrowser
rng=np.random.default_rng(42);a=ndtri(1-1e-6)
estimate,se,ess,z=gaussian_tail(a,10000,rng)
naive=(rng.normal(size=100000)>a)
print('umbral',a,'IS',estimate,'SE',se,'ESS pesos',ess,'eventos ponderados',np.count_nonzero(z))
print('IID',naive.mean(),'fallos',naive.sum(),'referencia 1e-6')

Exercises

ProofAntithetic covariance
Prove: Prove that an increasing integrand of uniform U has nonpositive antithetic covariance.
0
U and V are independent and uniform on [0,1].

Step 1 of 3. What is the sign of (f(U)−f(V))(f(1−U)−f(1−V))?

ProofOptimal control
Prove: Minimize the variance of Y−β(C−E C).
0
Var(C)>0 and second moments are finite.

Step 1 of 3. What is the variance as a function of β?

NumericCorrelation and cost
With ρ=0.95 and a control cost per sample 20% higher, what is the efficiency gain, previous variance per cost divided by the new one?
QuizChoosing a technique
For a symmetric integrand f(u)=f(1−u), what happens with antithetic pairs at the same number of evaluations?
CodeCross-entropy for a tail
Implement cross_entropy_is(log_target_indicator,family,n_iter,rho). The callback receives matrix x and returns (score, log_indicator), with zero inside the event and −inf outside. family contains mean, n, rng and threshold; fit the mean of an identity-covariance normal using p/q-weighted elites and quantile levels. Return the mean and history; the evaluation sample is independent.
import numpy as np
def cross_entropy_is(log_target_indicator,family,n_iter,rho):
  pass
Shift+Enter to run
Key idea
Reducing variance requires exploiting structure while keeping bias, tails, independence and total cost in view.