%%{init: {"flowchart": {"nodeSpacing": 18, "rankSpacing": 25}, "themeVariables": {"fontSize": "14px"}}}%%
flowchart LR
A["Integration"] --> B["Deterministic"]
A --> C["Sampling"]
B --> D["Trapezoid"]
B --> E["Gaussian"]
B --> F["QuadGK"]
C --> G["Monte Carlo"]
C --> H["Quasi-Monte Carlo"]
Computational Techniques 2
Integration
- Economic objectives often include an integral or expectation that must be evaluated numerically.
- This section moves from deterministic rules to sampling methods as the dimension of the problem increases.
- The examples follow Judd’s notes on numerical integration and Monte Carlo methods.
Type of Approach
- Numerical integration methods first divide into deterministic rules and sampling methods.
- Start with QuadGK for a general one-dimensional integral.
- Use Gaussian quadrature when the domain or probability distribution is known and the same integral is evaluated repeatedly.
- Move to Monte Carlo or quasi-Monte Carlo when the number of shocks or dimensions makes deterministic rules too expensive.
Example of Integration
The method will change throughout the section, but the quantity being approximated will remain the same.
Overview: A common benchmark makes the approximation error from each method easy to interpret.
Let \(Z\) follow a standard normal distribution and define
\[ Z\sim N(0,1), \qquad Q(\theta) = E\left[\exp(\theta Z)\right]. \]
- This expectation has the analytical value
\[ Q(\theta)=\exp\left(\frac{\theta^2}{2}\right). \]
- We use \(\theta=0.75\) to compare the numerical methods.
using Random, Statistics, Distributions, LinearAlgebra
using QuadGK, FastGaussQuadrature
using QuasiMonteCarlo
using ForwardDiff
using Zygote
using DataFrames
using Plotsstandard_normal = Normal()
evaluation_parameter = 0.75
expectation_integrand(θ, z) = exp(θ * z)
normal_weighted_integrand(θ, z) =
exp(θ * z - z^2 / 2) / sqrt(2π)
exact_expectation(θ) = exp(θ^2 / 2)
@show evaluation_parameter
@show exact_expectation(evaluation_parameter)
nothingevaluation_parameter = 0.75
exact_expectation(evaluation_parameter) = 1.3247847587288655
Deterministic Methods
The running example is a continuous integral, but a computer must reduce it to finitely many function evaluations.
Overview: Numerical integration replaces an area by a weighted sum.
Idea: Evaluate the function at selected nodes and combine those values with numerical weights.
Numerical integration replaces an area by a weighted sum:
\[ \int_a^b f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i). \]
Trapezoid Rule
- The trapezoid rule gives the simplest geometric illustration: it integrates a piecewise-linear approximation to \(f\).
Gaussian Quadrature
- The trapezoid rule uses evenly spaced nodes. Gaussian quadrature instead chooses nodes and weights that are efficient for a known domain or probability weight.
- Overview: Gaussian quadrature chooses both nodes and weights to extract as much accuracy as possible from a fixed number of evaluations.
- Idea: Start from a weighted integral:
\[ I(f)=\int_D \rho(x)f(x)\,dx. \]
- Fix the domain \(D\) and weight function \(\rho\).
- Construct the degree-\(n\) polynomial \(\pi_n\) that is orthogonal under \(\rho\).
- Use the \(n\) roots of \(\pi_n\) as the nodes \(x_i\).
- Set \(w_i=\int_D\rho(x)\ell_i(x)\,dx\), where \(\ell_i(x_j)=\mathbf{1}\{i=j\}\), and evaluate \(\sum_{i=1}^n w_i f(x_i)\).
- The resulting rule is exact for every polynomial of degree at most \(2n-1\).
- For a general integrand, accuracy depends on how well a polynomial of this degree approximates it; increase the number of nodes or use adaptive quadrature when the integrand is irregular.
- The nodes and weights depend on \(D\) and \(\rho\), not on the user’s integrand.
FastGaussQuadrature.jlsupplies the rules; the user supplies the economic integrand.
- Symmetry gives nodes \(-a,a\) with a common weight \(w\).
- Matching the integrals of \(1\) and \(x^2\) gives \(2w=2\) and \(2wa^2=2/3\), so \(w=1\) and \(a=1/\sqrt{3}\).
- Therefore, \(\int_{-1}^{1}f(x)\,dx\approx f(-1/\sqrt{3})+f(1/\sqrt{3})\), which is exact through degree three.
| Rule | Weighted integral | Nodes | Typical use |
|---|---|---|---|
| Gauss–Legendre | \(\int_{-1}^{1}f(x)\,dx\) | Roots of a Legendre polynomial | Bounded interval |
| Gauss–Hermite | \(\int_{-\infty}^{\infty}e^{-x^2}f(x)\,dx\) | Roots of a Hermite polynomial | Classical Hermite-weighted integral |
Gauss–Hermite with normalize=true |
\(\int_{-\infty}^{\infty}\phi(x)f(x)\,dx\) | Hermite nodes rescaled for \(\phi\) | Standard normal expectation |
- By default,
gausshermitereturns nodes \(x_i\) and weights \(w_i\) for
\[ \int_{-\infty}^{\infty}e^{-x^2}f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i), \qquad \sum_{i=1}^n w_i=\sqrt{\pi}. \]
- Setting
normalize=trueapplies \(z_i=\sqrt{2}x_i\) and \(\widetilde w_i=w_i/\sqrt{\pi}\), so
\[ E[f(Z)] = \int_{-\infty}^{\infty}\phi(z)f(z)\,dz \approx \sum_{i=1}^n \widetilde w_i f(z_i), \qquad \sum_{i=1}^n \widetilde w_i=1. \]
- Normalization changes the target weight and coordinate scale, not the order of accuracy of the rule.
- FastGaussQuadrature finds the polynomial roots with Newton’s method and a recurrence, with asymptotic formulas for large rules.
- It computes weights from those roots and derivatives; it does not optimize them separately for each integrand.
- The following code maps Gauss–Legendre nodes to a bounded interval and uses normalized Gauss–Hermite nodes for the running normal expectation.
legendre_nodes, legendre_weights = gausslegendre(5)
mapped_nodes = (legendre_nodes .+ 1) ./ 2
bounded_integrand(x) = exp(x)
legendre_estimate = sum(
(legendre_weights ./ 2) .* bounded_integrand.(mapped_nodes),
)
hermite_nodes, hermite_weights =
gausshermite(7; normalize = true)
gauss_hermite_expectation(θ) = sum(
hermite_weights .* expectation_integrand.(θ, hermite_nodes),
)
@show legendre_estimate
@show exp(1) - 1
@show gauss_hermite_expectation(evaluation_parameter)
nothinglegendre_estimate = 1.7182818284583914
exp(1) - 1 = 1.718281828459045
gauss_hermite_expectation(evaluation_parameter) = 1.3247847575514768
Adaptive Quadrature with QuadGK
- Gaussian quadrature uses a fixed rule chosen in advance. QuadGK instead checks local accuracy and refines only the intervals that are difficult to approximate.
- Overview: QuadGK is an adaptive method for general one-dimensional integrals.
- Idea: Compare nested Gauss–Kronrod estimates and subdivide an interval when their difference exceeds the error tolerance.
- Benefits:
- It concentrates function evaluations where they are needed.
- It returns an integral estimate and an error estimate and can handle unbounded intervals.
- Costs:
- An irregular integrand may require many subdivisions and function evaluations.
For each interval \(A=[a,b]\):
- Compute a Gauss estimate \(I_G(A)\) and a higher-order Kronrod estimate \(I_K(A)\) using nested evaluation points.
- Estimate the local error by \(e(A)=\left|I_K(A)-I_G(A)\right|\).
- If \(e(A)\) exceeds the tolerance, split \(A\) at \(m=(a+b)/2\) and repeat the calculation on \([a,m]\) and \([m,b]\).
The final integral is the sum of the accepted \(I_K(A)\) values. QuadGK.jl returns this estimate together with an estimated error.
- The code below evaluates the exponential term and normal density together to avoid overflow in the tails.
function quadgk_expectation(θ)
estimate, _ = quadgk(
z -> normal_weighted_integrand(θ, z),
-Inf,
Inf,
)
return estimate
end
quadgk_estimate, quadgk_error = quadgk(
z -> normal_weighted_integrand(evaluation_parameter, z),
-Inf,
Inf,
)
@show quadgk_estimate
@show quadgk_error
nothingquadgk_estimate = 1.3247847587288781
quadgk_error = 1.1079035021622087e-8
Sampling Methods
- Deterministic quadrature is effective in low dimensions, but a product rule with \(m\) nodes in each of \(d\) dimensions requires \(m^d\) evaluations.
- This growth motivates sampling methods when a model has many shocks.
Monte Carlo Integration
When deterministic grids become too large, Monte Carlo avoids constructing a grid over every combination of shocks.
Overview: Monte Carlo approximates an expectation with a random sample average.
Idea: Draw directly from the target distribution and give every observation equal weight.
Monte Carlo replaces the expectation by a sample average:
\[ E[g(Z)] \approx \frac{1}{N}\sum_{s=1}^N g(Z_s). \]
Distributions.jlgenerates the draws;Statistics.meanevaluates the approximation.- Its standard error decreases at the rate \(O(N^{-1/2})\).
mc_rng = MersenneTwister(2026)
mc_draws = rand(mc_rng, standard_normal, 1_000)
nothingmc_expectation(θ) =
mean(expectation_integrand.(θ, mc_draws))
@show mc_expectation(evaluation_parameter)
nothingmc_expectation(evaluation_parameter) = 1.2889057162192425
- Fixed draws make the numerical objective reproducible across optimizer evaluations.
Quasi-Monte Carlo: Halton Sequence
- A finite Monte Carlo sample may cluster in some regions and leave gaps in others. Quasi-Monte Carlo changes how the points are selected.
- Overview: Quasi-Monte Carlo replaces random draws with deterministic points that cover the unit cube more evenly.
- Idea: Reduce gaps in the sample while retaining the sample-average form of Monte Carlo integration.
- The Halton sequence constructs coordinate \(j\) with the radical inverse in a different prime base.
- Write the integer \(n\) in base \(b\):
\[ n=a_0+a_1b+a_2b^2+\cdots, \]
- The radical inverse reverses those digits across the radix point:
\[ \phi_b(n) = \frac{a_0}{b} + \frac{a_1}{b^2} + \frac{a_2}{b^3} +\cdots. \]
- In two dimensions, the points are
\[ \left(\phi_2(n),\phi_3(n)\right), \qquad n=1,2,\ldots. \]
- Use base 2 for the first coordinate and base 3 for the second coordinate.
| \(n\) | Base-2 reversal | Base-3 reversal | Halton point |
|---|---|---|---|
| \(1\) | \(1_2\rightarrow 0.1_2=1/2\) | \(1_3\rightarrow 0.1_3=1/3\) | \((1/2,1/3)\) |
| \(2\) | \(10_2\rightarrow 0.01_2=1/4\) | \(2_3\rightarrow 0.2_3=2/3\) | \((1/4,2/3)\) |
| \(3\) | \(11_2\rightarrow 0.11_2=3/4\) | \(10_3\rightarrow 0.01_3=1/9\) | \((3/4,1/9)\) |
| \(4\) | \(100_2\rightarrow 0.001_2=1/8\) | \(11_3\rightarrow 0.11_3=4/9\) | \((1/8,4/9)\) |
- The base-2 coordinate therefore begins \(1/2,1/4,3/4,1/8,\ldots\), rather than \(1/2,1/4,1/8,\ldots\). Reversing the digits first places points in different halves and quarters before refining the grid.
- Consecutive indices move systematically among halves, quarters, thirds, and ninths of the unit square instead of clustering randomly.
QuasiMonteCarlo.jlprovides Halton and other sampling rules.
halton_uniform = vec(
QuasiMonteCarlo.sample(
1_000,
[0.0],
[1.0],
HaltonSample(),
),
)
halton_draws = quantile.(Ref(standard_normal), halton_uniform)
nothinghalton_expectation(θ) =
mean(expectation_integrand.(θ, halton_draws))
@show halton_expectation(evaluation_parameter)
nothinghalton_expectation(evaluation_parameter) = 1.3141204576832974
- An ordinary i.i.d. Monte Carlo standard error does not apply to a deterministic Halton sequence.
Comparing the Methods
- No method is best for every problem. Compare the methods on the same expectation before applying the decision rules below.
- Here, every approximation is compared with the analytical value at the same parameter.
integration_methods = [
"QuadGK" => quadgk_expectation,
"Gauss–Hermite" => gauss_hermite_expectation,
"Monte Carlo" => mc_expectation,
"Halton" => halton_expectation,
]
exact_value = exact_expectation(evaluation_parameter)
method_names = first.(integration_methods)
method_estimates = [
method(evaluation_parameter)
for method in last.(integration_methods)
]
method_errors = abs.(method_estimates .- exact_value)
integration_comparison = DataFrame(
"Method" => method_names,
"Estimate" => round.(method_estimates; sigdigits = 8),
"Exact value" => fill(
round(exact_value; sigdigits = 8),
length(integration_methods),
),
"Absolute error" => round.(method_errors; sigdigits = 4),
)
integration_comparison| Row | Method | Estimate | Exact value | Absolute error |
|---|---|---|---|---|
| String | Float64 | Float64 | Float64 | |
| 1 | QuadGK | 1.32478 | 1.32478 | 1.266e-14 |
| 2 | Gauss–Hermite | 1.32478 | 1.32478 | 1.177e-9 |
| 3 | Monte Carlo | 1.28891 | 1.32478 | 0.03588 |
| 4 | Halton | 1.31412 | 1.32478 | 0.01066 |
- The Monte Carlo result depends on the realized sample. This comparison is a diagnostic, not a general ranking.
| Method | Useful starting point | Main limitation |
|---|---|---|
| Trapezoid | Geometric intuition or values on a fixed grid | Slow on a coarse grid |
| QuadGK | General one-dimensional integral | Adaptive evaluation can be costly |
| Gaussian | Smooth integral with a known domain or weight | Product rules grow as \(m^d\) |
| Monte Carlo | High-dimensional expectations | Slow \(N^{-1/2}\) convergence |
| Quasi-Monte Carlo | Smooth transformed integrands | No ordinary i.i.d. standard error |
- Do not rely on a single numerical approximation.
- For deterministic rules, tighten the tolerance or increase the number of nodes. For Monte Carlo, report a standard error and increase the number of draws.
- Deterministic QMC has no ordinary i.i.d. standard error; increase the number of points or use independent randomizations.
Differentiation
- Gradient-based solvers require derivatives of the numerical objective.
- This section uses finite differences to explain numerical derivative error and forward-mode automatic differentiation for routine implementation.
Finite Differences
An analytical derivative is an ideal benchmark, but it may be inconvenient for a long numerical objective. Nearby function values provide the simplest numerical approximation.
Overview: Finite differences are introduced here to explain step-size error and to provide an independent check.
Idea: Approximate the local slope using function values on either side of the evaluation point.
A central difference uses
\[ f'(x) \approx \frac{f(x+h)-f(x-h)}{2h}. \]
- The figure below applies this formula to the running expectation:
\[ Q(\theta) = E[\exp(\theta Z)] = \exp\left(\frac{\theta^2}{2}\right), \qquad Q'(\theta) = \theta\exp\left(\frac{\theta^2}{2}\right). \]
- At \(\theta=0.75\), the exact derivative is
\[ Q'(0.75) = 0.75\exp\left(\frac{0.75^2}{2}\right) \approx 0.993588569. \]
- For each step size \(h\), the vertical axis reports
\[ \operatorname{error}(h) = \left| \frac{Q(0.75+h)-Q(0.75-h)}{2h} - Q'(0.75) \right|. \]
- For example, \(h=10^{-5}\) gives an estimate of \(0.9935885691\) and an absolute error of approximately \(5.15\times 10^{-11}\). Because the exact derivative is close to one, the absolute and relative errors have similar magnitudes in this example.
- Large steps create truncation error; very small steps amplify floating-point cancellation.
- Finite differences remain useful as an independent derivative check.
Forward-Mode Automatic Differentiation
- Finite differences require a step size and therefore face a tradeoff between truncation and floating-point error. Automatic differentiation removes that choice.
- Overview: Automatic differentiation computes derivatives of the executed program without perturbing its inputs.
- Idea: Apply the chain rule to each elementary operation in the program.
- A dual number stores the function value and derivative information together. Start with the simplest seed:
\[ f(x+\epsilon) = f(x)+\epsilon f'(x), \qquad \epsilon^2=0. \]
- Here, \(\epsilon\) is a formal marker, not a small real step. The ordinary component stores \(f(x)\), while the coefficient of \(\epsilon\) stores \(f'(x)\).
- For example, if \(f(x)=x^2\) and \(x=3\),
\[ (3+\epsilon)^2 = 9+6\epsilon. \]
- More generally, attach a seed \(\dot x\) to specify the input direction:
\[ f(x+\epsilon\dot x) = f(x)+\epsilon f'(x)\dot x. \]
- Thus, \(\epsilon\) separates derivative information from the ordinary value, while \(\dot x\) specifies the direction and scale of the derivative. Set \(\dot x=1\) for an ordinary scalar derivative; here, \(\dot x\) is a tangent seed, not a time derivative.
ForwardDiff.jlhandles the dual-number propagation.
forward_derivative = ForwardDiff.derivative(
exact_expectation,
evaluation_parameter,
)
@show forward_derivative
nothingforward_derivative = 0.993588569046649
| Mathematical object | ForwardDiff call |
|---|---|
| Scalar derivative | derivative |
| Gradient | gradient |
| Jacobian | jacobian |
| Hessian | hessian |
Forward and Reverse Modes
- Forward and reverse modes apply the same chain rule in opposite directions. Their difference is computational cost, not the derivative they return.
- Consider the scalar objective
\[ y=f(x_1,x_2) =(x_1-1)^2+2(x_2+1)^2. \]
- At \((x_1,x_2)=(0,0)\):
- Forward mode first seeds the \(x_1\) direction, then the \(x_2\) direction, and propagates each derivative from inputs to output. Conceptually, the two directions produce \(\partial y/\partial x_1=-2\) and \(\partial y/\partial x_2=4\).
- Reverse mode first evaluates \(y\), sets the output sensitivity to \(\bar y=1\), and propagates sensitivities backward through the recorded operations. One reverse pass produces both input sensitivities \((\bar x_1,\bar x_2)=(-2,4)\).
quadratic_objective(parameters) =
(parameters[1] - 1)^2 +
2 * (parameters[2] + 1)^2
evaluation_parameters = [0.0, 0.0]
forward_gradient = ForwardDiff.gradient(
quadratic_objective,
evaluation_parameters,
)
reverse_gradient = Zygote.gradient(
quadratic_objective,
evaluation_parameters,
)[1]
@show forward_gradient
@show reverse_gradient
nothingforward_gradient = [-2.0, 4.0]
reverse_gradient = [-2.0, 4.0]
- More generally, for \(f:\mathbb{R}^n\rightarrow\mathbb{R}^m\) with Jacobian \(J\):
- Forward mode propagates \(Jv\) and scales mainly with the number of input directions \(n\).
- Reverse mode propagates \(J^\top u\) and scales mainly with the number of output directions \(m\), but it must store or recompute intermediate values.
| Mode | Prefer when | Julia backend |
|---|---|---|
| Forward | Few inputs or many outputs | ForwardDiff |
| Reverse | Many inputs and a scalar or few outputs | Zygote |
- Julia usually selects the mode through the package:
ForwardDiffuses forward mode andZygoteuses reverse mode.ForwardDiffdoes not have a forward-versus-reverse option. - Forward mode remains the practical default here because the examples have one or a few parameters.
- Hold quadrature nodes or simulation draws fixed and let AD differentiate the resulting finite approximation.
- Under standard regularity conditions and a fixed distribution, the derivative of an expectation equals the expectation of the derivative.
- AD removes finite-difference error, not integration error, and differentiates the executed program rather than the intended model.
- Nondifferentiable operations, discrete choices, branches, and nested solvers may require special treatment; check a few derivatives analytically or with finite differences.
Parallel Computing
- Integration, simulation, and bootstrap often repeat the same computation across independent draws or samples.
Cores, Threads, and Tasks
- Parallel computing divides work across multiple computing resources. This section focuses on CPU threads.
- A Julia thread is a worker inside one Julia process. A task is a unit of work that Julia assigns to an available thread.
- Threaded parallel execution requires more than one Julia thread.
@show Sys.CPU_THREADS
@show Threads.nthreads()
nothingSys.CPU_THREADS = 4
Threads.nthreads() = 4
Sys.CPU_THREADSreports the logical CPUs available to the machine.Threads.nthreads()reports the threads available to the Julia process.- Choose the thread count when Julia starts, for example with
julia --threads=auto.
Two Limits
Amdahl’s Law
- Let \(p\) be the share of work that can run in parallel and let \(P\) be the number of threads. The maximum speedup is
\[ S(P) = \frac{1}{(1-p)+p/P}. \]
- If \(p=0.8\), the speedup cannot exceed \(1/(1-p)=5\), even with infinitely many threads.
Task Overhead
- Creating, scheduling, and synchronizing tasks takes time.
- Parallelization helps only when each task is large enough to cover these costs.
- First-call compilation is separate from task overhead. Run the function once before timing it.
Threads in Julia
Threads.@threadsdistributes independent loop iterations across the available Julia threads and waits until the loop is complete.- Iterations can run in any order, so each iteration should use its own random number generator and write to a separate output location.
Example: Parallel OLS Bootstrap
- Generate data from
\[ y_i=\beta_0+\beta_1x_i+\varepsilon_i. \]
- Each bootstrap task resamples the observations and estimates OLS independently.
- Matrix factorizations may already use multiple threads through a native BLAS/LAPACK library. If the outer bootstrap loop uses Julia threads, set BLAS to one thread to avoid oversubscription.
- For one large factorization, make the opposite choice: let BLAS use multiple threads and do not also split the same work with
Threads.@threads.
function simulate_ols_data(; seed, n = 100_000)
rng = MersenneTwister(seed)
regressor = randn(rng, n)
design_matrix = hcat(ones(n), regressor)
outcome =
design_matrix * [1.0, 2.0] +
randn(rng, n)
return design_matrix, outcome
end
estimate_ols(; design_matrix, outcome) =
design_matrix \ outcome
function bootstrap_ols(; design_matrix, outcome, seed)
rng = MersenneTwister(seed)
sample_size = size(design_matrix, 1)
sample_indices = rand(rng, 1:sample_size, sample_size)
return estimate_ols(
design_matrix = design_matrix[sample_indices, :],
outcome = outcome[sample_indices],
)
end
bootstrap_design, bootstrap_outcome =
simulate_ols_data(seed = 2026)
@show size(bootstrap_design, 1)
@show size(bootstrap_design, 2)
nothingsize(bootstrap_design, 1) = 100000
size(bootstrap_design, 2) = 2
BLAS.set_num_threads(1)
bootstrap_repetitions = 16
bootstrap_estimates = Matrix{Float64}(
undef,
size(bootstrap_design, 2),
bootstrap_repetitions,
)
Threads.@threads for repetition in 1:bootstrap_repetitions
bootstrap_estimates[:, repetition] = bootstrap_ols(
design_matrix = bootstrap_design,
outcome = bootstrap_outcome,
seed = repetition,
)
end
bootstrap_mean = vec(mean(bootstrap_estimates; dims = 2))
bootstrap_standard_deviation =
vec(std(bootstrap_estimates; dims = 2))
@show size(bootstrap_estimates)
@show bootstrap_mean
@show bootstrap_standard_deviation
nothingsize(bootstrap_estimates) = (2, 16)
bootstrap_mean = [0.9981003263090004, 1.99924741543754]
bootstrap_standard_deviation = [0.003059582759084851, 0.0022740259410527755]
From Threads to Clusters
- Julia threads divide work within one process and one computing node.
- A cluster distributes larger jobs across processes or computing nodes.
- Divide large jobs at the cluster level and use Julia threads for smaller repeated tasks within each job.