Computational Techniques
Motivation and Learning Goals
- We often read about computations performed in research papers, but it is not always clear how to implement them in practice.
- Learn how to implement computational techniques relevant to this type of research in Julia.
Nonlinear equations
- An equation solver searches for \(x^\ast\) such that
\[ F(x^\ast)=0. \]
- In economics, \(F\) may represent excess demand, equilibrium conditions, or first-order conditions.
Bisection
- Overview: Bisection is the simplest and most robust method for solving a scalar equation when a bracket is available.
- Idea: The intermediate value theorem implies that a continuous function has a root inside an interval satisfying \(f(a_0)f(b_0)<0\).
- Benefits:
- It always keeps a root inside the bracket.
- It does not need derivatives.
- Costs:
- It converges slowly.
- It needs a scalar equation and a starting bracket.
- Input: A continuous function \(f\), a bracket \([a_0,b_0]\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Assumption: \(f(a_0)f(b_0)\leq 0\).
\[ [a_{k+1},b_{k+1}] = \begin{cases} [a_k,m_k], & f(a_k)f(m_k)\leq 0,\\ [m_k,b_k], & \text{otherwise}, \end{cases} \qquad m_k=\frac{a_k+b_k}{2}. \]
- Update: For \(k=0,\ldots,K-1\):
- Set \(m_k=(a_k+b_k)/2\).
- Stop and return \(m_k\) if \(|f(m_k)|\leq\varepsilon\).
- Retain the half interval on which the function changes sign.
- Stop: Also stop when \((b_k-a_k)/2\leq\varepsilon\).
- Output: The approximate root, residual, iteration count, and solver status.
- Example problem: find the market-clearing price when demand is \(D(p)=10/p\) and supply is \(S(p)=5\):
\[ \text{find }p^\ast\in[0.5,4] \quad\text{such that}\quad F(p^\ast)=\frac{10}{p^\ast}-5=0. \]
using LinearAlgebra
using ForwardDiff
import Roots
excess_demand(price) = 10 / price - 5
roots_bisection_price = Roots.find_zero(
excess_demand,
(0.5, 4.0),
Roots.Bisection(),
)
roots_bisection_residual = excess_demand(roots_bisection_price)
@show roots_bisection_price roots_bisection_residualroots_bisection_price = 2.0
roots_bisection_residual = 0.0
0.0
Newton’s method
- Bisection needs an interval known to contain a root. When such a bracket is unavailable but derivatives can be evaluated, Newton’s method provides a local alternative.
- Overview: Newton’s method is a local root-finding method based on derivatives.
- Idea: Replace \(F\) by its first-order approximation and use the root of the local linear model as the next iterate.
- Benefits:
- It converges very quickly near a regular root.
- It works for both scalar equations and systems.
- Costs:
- It needs a derivative or Jacobian.
- A poor starting value or an unstable Jacobian can cause failure.
- Input: \(F\), its Jacobian \(J_F\), an initial value \(x_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
\[ J_F(x_k)\Delta x_k=-F(x_k), \qquad x_{k+1}=x_k+\Delta x_k. \]
- Update: For \(k=0,\ldots,K-1\):
- Solve \(J_F(x_k)\Delta x_k=-F(x_k)\).
- Set \(x_{k+1}=x_k+\Delta x_k\).
- Stop if \(\lVert F(x_{k+1})\rVert_\infty\leq\varepsilon\).
- Failure check: Stop with a failure status if the Newton system cannot be solved reliably.
- Output: The approximate root, residual, iteration count, and solver status.
- Example problem: solve the same market-clearing equation from \(p_0=1\):
\[ \text{find }p^\ast>0 \quad\text{such that}\quad F(p^\ast)=\frac{10}{p^\ast}-5=0. \]
excess_demand_derivative(price) = -10 / price^2
import Roots
roots_newton_price = Roots.find_zero(
(excess_demand, excess_demand_derivative),
1.0,
Roots.Newton(),
)
roots_newton_residual = excess_demand(roots_newton_price)
@show roots_newton_price roots_newton_residualroots_newton_price = 2.0
roots_newton_residual = 0.0
0.0
- For larger systems,
NLsolve.jlandNonlinearSolve.jlconstruct or approximate the Jacobian and solve the Newton system.
Broyden method
- Newton’s method repeatedly evaluates or constructs the Jacobian. When that calculation is expensive, Broyden’s method replaces it with an updated approximation.
- Overview: Broyden’s method is a quasi-Newton root finder that avoids recomputing the full Jacobian at every iteration.
- Idea: Use successive changes in \(x\) and \(F(x)\) to update a Jacobian approximation \(B_k\) through a secant condition.
- Benefits:
- It does not rebuild the full Jacobian at every step.
- It is useful when computing the Jacobian is expensive.
- Costs:
- The Jacobian approximation can become inaccurate.
- It can be less reliable than Newton’s method.
- Input: \(F\), an initial value \(x_0\), an initial Jacobian approximation \(B_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Set \(s_k=x_{k+1}-x_k\) and \(y_k=F(x_{k+1})-F(x_k)\), and update:
\[ B_{k+1} = B_k+\frac{(y_k-B_ks_k)s_k'}{s_k's_k}. \]
- Update: For \(k=0,\ldots,K-1\):
- Solve \(B_ks_k=-F(x_k)\) and set \(x_{k+1}=x_k+s_k\).
- Stop if \(\lVert F(x_{k+1})\rVert_\infty\leq\varepsilon\).
- Set \(y_k=F(x_{k+1})-F(x_k)\).
- Use \((s_k,y_k)\) to update \(B_k\) by the rank-one formula above.
- Failure check: Stop if the approximate Newton system cannot be solved or if the rank-one update becomes numerically unstable.
- Output: The approximate root, residual, iteration count, and solver status.
- Example problem: solve a two-equation nonlinear system from \(x_0=(5,1.5)'\):
\[ \text{find }x^\ast= \begin{bmatrix} x_1^\ast\\ x_2^\ast \end{bmatrix} \quad\text{such that}\quad F(x^\ast)= \begin{bmatrix} (x_1^\ast)^2+x_2^\ast-37\\ x_1^\ast-(x_2^\ast)^2-5 \end{bmatrix} = \begin{bmatrix} 0\\ 0 \end{bmatrix}. \]
import NonlinearSolve
equilibrium_system(x) = [
x[1]^2 + x[2] - 37,
x[1] - x[2]^2 - 5,
]
broyden_problem = NonlinearSolve.NonlinearProblem(
(x, _) -> equilibrium_system(x),
[5.0, 1.5],
)
broyden_result = NonlinearSolve.solve(
broyden_problem,
NonlinearSolve.Broyden(init_jacobian = Val(:true_jacobian));
abstol = 1e-10,
reltol = 1e-10,
maxiters = 100,
)
broyden_solution = broyden_result.u
broyden_residual = equilibrium_system(broyden_solution)
broyden_status = broyden_result.retcode
@show broyden_solution broyden_residual broyden_statusbroyden_solution = [5.999999999999929, 0.9999999999999457]
broyden_residual = [-9.094947017729282e-13, 3.730349362740526e-14]
broyden_status = SciMLBase.ReturnCode.Success
ReturnCode.Success = 1
NonlinearSolve.jlprovidesBroyden()andLimitedMemoryBroyden().
Fixed-point iteration
- Broyden treats the system as \(F(x)=0\). If the same problem has a useful fixed-point form \(x=G(x)\), fixed-point iteration directly applies that mapping.
- Overview: Fixed-point iteration repeatedly applies a mapping to solve \(x=G(x)\).
- Idea: Start from \(x_0\) and use the current output as the next input.
- Benefits:
- It is simple and does not need derivatives.
- It works well when the mapping is a contraction.
- Costs:
- A poor choice of the mapping can cause divergence.
- Convergence can be slow.
- Input: A mapping \(G\), an initial value \(x_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Update: For \(k=0,\ldots,K-1\), set:
\[ x_{k+1}=G(x_k). \]
- Stop if \(\lVert x_{k+1}-x_k\rVert_\infty\leq\varepsilon\).
- If the full update is unstable, use a damping parameter \(\lambda\in(0,1]\):
\[ x_{k+1}=(1-\lambda)x_k+\lambda G(x_k). \]
- Output: The approximate fixed point, iteration count, and solver status.
- Example problem: find the fixed point of the cosine function:
\[ \text{find }x^\ast \quad\text{such that}\quad x^\ast=\cos(x^\ast). \]
import NLsolve
fixed_point_result = NLsolve.fixedpoint(
value -> cos.(value),
[1.0];
inplace = false,
xtol = 1e-10,
ftol = 1e-10,
)
fixed_point_solution = only(fixed_point_result.zero)
fixed_point_residual =
only(cos.(fixed_point_result.zero) - fixed_point_result.zero)
fixed_point_converged = NLsolve.converged(fixed_point_result)
@show fixed_point_solution fixed_point_residual fixed_point_convergedfixed_point_solution = 0.7390851332151607
fixed_point_residual = 0.0
fixed_point_converged = true
true
Gauss–Jacobi iteration
- Fixed-point iteration gives the general update \(x_{k+1}=G(x_k)\). For a vector mapping, Gauss–Jacobi computes every component of the next vector simultaneously.
- Overview: Gauss–Jacobi is a simultaneous fixed-point method for a vector equation \(x=G(x)\).
- Idea: Compute every new component from the same old vector \(x_k\).
- Benefits:
- The components can be updated in parallel.
- The component order does not affect the update.
- Costs:
- It may require many iterations.
- It can fail when the mapping is not contractive.
- Input: A mapping \(G:\mathbb{R}^n\rightarrow\mathbb{R}^n\), an initial value \(x_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Update: For \(k=0,\ldots,K-1\), compute all components from \(x_k\):
\[ x_{i,k+1} = G_i(x_{1,k},\ldots,x_{n,k}), \qquad i=1,\ldots,n. \]
- Replace \(x_k\) only after all new components have been computed.
- Stop if \(\lVert x_{k+1}-x_k\rVert_\infty\leq\varepsilon\).
- Output: The approximate fixed point, iteration count, and solver status.
- Example problem: find the Cournot equilibrium by updating both firms’ quantities at the same time.
- Let \(P=10-(q_1+q_2)\) and \(C_i(q_i)=2q_i\). Each firm’s best response is:
\[ \operatorname{BR}_i(q_j) = \max\left\{0,\frac{8-q_j}{2}\right\}. \]
- The equilibrium solves:
\[ \text{find }(q_1^\ast,q_2^\ast) \quad\text{such that}\quad \begin{cases} q_1^\ast=\operatorname{BR}_1(q_2^\ast),\\ q_2^\ast=\operatorname{BR}_2(q_1^\ast). \end{cases} \]
best_response(other_quantity; demand_intercept = 10.0, slope = 1.0, cost = 2.0) =
max(0.0, (demand_intercept - cost - slope * other_quantity) / (2slope))
function cournot_jacobi(initial_value; atol = 1e-10, maxiter = 1_000)
quantities = copy(initial_value)
for iteration in 1:maxiter
new_quantities = [
best_response(quantities[2]),
best_response(quantities[1]),
]
norm(new_quantities - quantities, Inf) <= atol &&
return new_quantities
quantities = new_quantities
end
error("Gauss--Jacobi iteration did not converge.")
end
cournot_jacobi_solution = cournot_jacobi([0.0, 0.0])
@show cournot_jacobi_solutioncournot_jacobi_solution = [2.666666666686069, 2.666666666686069]
2-element Vector{Float64}:
2.666666666686069
2.666666666686069
Gauss–Seidel iteration
- Gauss–Jacobi waits until every component has been computed before replacing the old vector. Gauss–Seidel instead uses each new component immediately.
- Overview: Gauss–Seidel is a sequential fixed-point method for a vector equation \(x=G(x)\).
- Idea: Use each new component as soon as it has been computed.
- Benefits:
- Each update uses the newest available values.
- It often needs fewer iterations than Gauss–Jacobi.
- Costs:
- The path can depend on the component order.
- The sequential updates are harder to parallelize.
- Input: A mapping \(G:\mathbb{R}^n\rightarrow\mathbb{R}^n\), an initial value \(x_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Update: For \(k=0,\ldots,K-1\), update components in order:
\[ x_{i,k+1} = G_i( x_{1,k+1},\ldots,x_{i-1,k+1}, x_{i,k},\ldots,x_{n,k} ), \qquad i=1,\ldots,n. \]
- Stop if \(\lVert x_{k+1}-x_k\rVert_\infty\leq\varepsilon\).
- Output: The approximate fixed point, iteration count, and solver status.
- Example problem: solve the same Cournot system, but update firm 2 after updating firm 1:
\[ q_{1,k+1}=\operatorname{BR}_1(q_{2,k}), \qquad q_{2,k+1}=\operatorname{BR}_2(q_{1,k+1}). \]
function cournot_gauss_seidel(initial_value; atol = 1e-10, maxiter = 1_000)
quantities = copy(initial_value)
for iteration in 1:maxiter
new_q1 = best_response(quantities[2])
new_q2 = best_response(new_q1)
new_quantities = [new_q1, new_q2]
norm(new_quantities - quantities, Inf) <= atol &&
return new_quantities
quantities = new_quantities
end
error("Gauss--Seidel iteration did not converge.")
end
cournot_gauss_seidel_solution = cournot_gauss_seidel([0.0, 0.0])
@show cournot_gauss_seidel_solutioncournot_gauss_seidel_solution = [2.666666666686069, 2.6666666666569654]
2-element Vector{Float64}:
2.666666666686069
2.6666666666569654
Choosing a method
Suggested starting point
- The tree summarizes the choice after the methods above have been introduced.
%%{init: {"themeVariables": {"fontSize": "20px"}, "flowchart": {"nodeSpacing": 30, "rankSpacing": 35}}}%%
flowchart LR
A["Solve F(x) = 0"] --> B(["Scalar or system?"])
B -->|Scalar| C(["Bracket available?"])
C -->|Yes| D["Bisection"]
C -->|No| E["Newton"]
B -->|System| F(["Natural fixed-point form?"])
F -->|Yes| G["Fixed-point iteration,<br/>Gauss--Jacobi, or Gauss--Seidel"]
F -->|No| H(["Jacobian available?"])
H -->|Yes| I["Newton"]
H -->|No| J["Broyden"]
- Fixed-point methods require an appropriate mapping \(G\).
Benefits and costs
| Method | Benefits | Costs |
|---|---|---|
| Bisection | Robust and derivative-free | Slow; requires a scalar bracket |
| Newton | Fast near a regular root; handles systems | Requires derivatives or a Jacobian |
| Broyden | Avoids rebuilding the full Jacobian | The Jacobian approximation may deteriorate |
| Fixed-point iteration | Simple and derivative-free | Convergence depends on the mapping |
| Gauss–Jacobi | Allows parallel component updates | Can be slow; requires a contractive mapping |
| Gauss–Seidel | Uses new component values immediately | Sequential and sensitive to update order |
Unconstrained optimization
- An unconstrained optimizer searches for:
\[ \theta^\ast=\arg\min_{\theta\in\mathbb{R}^p}Q(\theta). \]
- At an interior solution, \(\nabla Q(\theta^\ast)=0\).
- Optimization uses equation-solving methods but must distinguish minima, maxima, and saddle points.
Newton–Raphson
- Newton’s root-finding method solves first-order conditions. For optimization, the same local approximation is applied to \(\nabla Q(\theta^\ast)=0\), with the Hessian providing the Jacobian.
- Overview: Newton–Raphson is a second-order optimization method that uses the gradient and Hessian.
- Idea: Minimize a local quadratic approximation to the objective at each iterate.
- Benefits:
- It can converge very quickly near the optimum.
- The Hessian uses curvature information directly.
- Costs:
- Building and solving with the Hessian can be expensive.
- An indefinite Hessian can give a poor direction.
- Input: \(Q\), its gradient and Hessian, an initial value \(\theta_0\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Use the local quadratic approximation:
\[ Q(\theta_k+s) \approx Q(\theta_k) +\nabla Q(\theta_k)'s +\frac{1}{2}s'H(\theta_k)s. \]
- Solve for the Newton step:
\[ H(\theta_k)s_k=-\nabla Q(\theta_k). \]
- Update: Set \(\theta_{k+1}=\theta_k+s_k\).
- Stop: Return \(\theta_{k+1}\) when \(\lVert\nabla Q(\theta_{k+1})\rVert_\infty\leq\varepsilon\).
- Failure check: Stop or safeguard the step if the Hessian system cannot be solved reliably.
- Output: The approximate minimizer, objective value, gradient norm, iteration count, and solver status.
- Illustration: hold the mean fixed and consider the one-dimensional objective
\[ q(\eta)=\eta+2\exp(-2\eta), \qquad \eta^\ast=\log 2. \]
- Starting from \(\eta_0=1\), Newton–Raphson minimizes the local quadratic approximation to obtain \(\eta_1\).
- Example problem: for observations \(y_1,\ldots,y_n\), minimize the average negative Gaussian log-likelihood up to an additive constant.
- Use \(\eta=\log\sigma\) so that \(\sigma\) remains positive:
\[ \min_{\mu,\eta\in\mathbb{R}} Q(\mu,\eta) = \eta +\frac{1}{2n\exp(2\eta)} \sum_{i=1}^n(y_i-\mu)^2, \qquad \eta=\log\sigma. \]
using Random
using Statistics
using Optim
Random.seed!(1234)
sample = 1.5 .+ 0.8 .* randn(500)
function normal_negative_log_likelihood(parameters)
mean_parameter, log_standard_deviation = parameters
centered = sample .- mean_parameter
return log_standard_deviation +
sum(abs2, centered) /
(2length(sample) * exp(2log_standard_deviation))
end
function likelihood_gradient!(storage, parameters)
storage .= ForwardDiff.gradient(normal_negative_log_likelihood, parameters)
return storage
end
function likelihood_hessian!(storage, parameters)
storage .= ForwardDiff.hessian(normal_negative_log_likelihood, parameters)
return storage
end
initial_parameters = [0.0, 0.0]
newton_result = Optim.optimize(
normal_negative_log_likelihood,
likelihood_gradient!,
likelihood_hessian!,
initial_parameters,
Optim.Newton(),
)
newton_estimate = Optim.minimizer(newton_result)
newton_analytical_solution = [
mean(sample),
log(std(sample; corrected = false)),
]
@show newton_estimate newton_analytical_solutionnewton_estimate = [1.4235855037867489, -0.14535454625277186]
newton_analytical_solution = [1.4235855036508538, -0.1453545458141886]
2-element Vector{Float64}:
1.4235855036508538
-0.1453545458141886
Quasi-Newton methods
- Newton–Raphson requires a new Hessian calculation and linear solve at each iteration. Quasi-Newton methods reduce this cost by approximating curvature from successive gradients.
- Overview: Quasi-Newton methods use gradient changes to approximate the inverse Hessian instead of calculating the Hessian directly.
- Idea: For
\[ s_k=\theta_{k+1}-\theta_k, \qquad y_k=\nabla Q(\theta_{k+1})-\nabla Q(\theta_k), \]
update an inverse-Hessian approximation \(H_{k+1}\) so that
\[ H_{k+1}y_k=s_k. \]
- Benefits:
- They do not need the full Hessian.
- They are usually a practical default for smooth estimation problems.
- Costs:
- They depend on good scaling and a good line search.
- The two methods differ mainly in how they represent \(H_k\):
- BFGS: stores and updates the full \(p\times p\) matrix. It uses \(O(p^2)\) memory and is useful for moderate \(p\).
- L-BFGS: stores only the most recent \(m\) pairs \((s_i,y_i)\). It uses \(O(mp)\) memory and is useful when \(p\) is large.
- Example problem: use both methods to minimize the Gaussian objective \(Q(\mu,\eta)\) from \((\mu_0,\eta_0)=(0,0)\).
bfgs_result = Optim.optimize(
normal_negative_log_likelihood,
initial_parameters,
Optim.BFGS();
autodiff = :forward,
)
lbfgs_result = Optim.optimize(
normal_negative_log_likelihood,
initial_parameters,
Optim.LBFGS();
autodiff = :forward,
)
bfgs_solution = Optim.minimizer(bfgs_result)
lbfgs_solution = Optim.minimizer(lbfgs_result)
@show bfgs_solution lbfgs_solutionbfgs_solution = [1.4235855036481526, -0.14535454580261964]
lbfgs_solution = [1.4235855033410831, -0.1453545430113449]
2-element Vector{Float64}:
1.4235855033410831
-0.1453545430113449
Golden-section search
- Newton and quasi-Newton methods use derivatives in multivariate problems. For a bounded scalar problem without derivatives, golden-section search contracts the interval directly.
- Overview: Golden-section search is a bounded, derivative-free method for minimizing a scalar objective.
- Idea: Place interior points using the golden ratio so that one previous function evaluation can be reused after the interval contracts.
- Benefits:
- It does not need derivatives.
- After initialization, each step needs only one new function evaluation.
- Costs:
- It needs a bounded, unimodal scalar problem.
- It is slower than a good derivative-based method.
- Input: A scalar objective \(q\), an interval \([a_0,b_0]\), a tolerance \(\varepsilon\), and a maximum iteration count \(K\).
- Set
\[ \tau=\frac{\sqrt{5}-1}{2}, \qquad c_k=b_k-\tau(b_k-a_k), \qquad d_k=a_k+\tau(b_k-a_k). \]
- Update the interval by
\[ [a_{k+1},b_{k+1}] = \begin{cases} [a_k,d_k], & q(c_k)\leq q(d_k),\\ [c_k,b_k], & q(c_k)>q(d_k). \end{cases} \]
- The identity \(1-\tau=\tau^2\) makes one old interior point an interior point of the new interval, so each update requires only one new evaluation.
- Stop when \(b_k-a_k\leq\varepsilon\) and return \((a_k+b_k)/2\).
- Output: The approximate minimizer, objective value, iteration count, and solver status.
- Example problem: hold \(\eta=\log\widehat{\sigma}\) fixed and minimize the profile objective over a bounded interval:
\[ \min_{\mu\in[-1,4]} Q\left(\mu,\log\widehat{\sigma}\right), \qquad \widehat{\sigma} = \left[ \frac{1}{n}\sum_{i=1}^n(y_i-\overline{y})^2 \right]^{1/2}. \]
profile_objective(mean_parameter) =
normal_negative_log_likelihood([
mean_parameter,
log(std(sample; corrected = false)),
])
golden_result = Optim.optimize(
profile_objective,
-1.0,
4.0,
Optim.GoldenSection(),
)
golden_solution = Optim.minimizer(golden_result)
@show golden_solutiongolden_solution = 1.4235855073024446
1.4235855073024446
Nelder–Mead
- Golden-section search is derivative-free but restricted to one dimension. Nelder–Mead extends derivative-free local search to a small multivariate problem by moving a simplex.
- Overview: Nelder–Mead is a derivative-free multivariate method that searches with a simplex.
- Idea: Move and reshape the simplex through reflection, expansion, contraction, and shrinkage according to the vertex objective values.
- Benefits:
- It does not need derivatives.
- It is simple and useful in low dimensions.
- Costs:
- It scales poorly as dimension grows.
- It may stop without reaching a good minimum.
- Input: An objective \(Q\), an initial simplex with \(p+1\) vertices, a parameter tolerance \(\varepsilon_x\), an objective tolerance \(\varepsilon_Q\), and a maximum iteration count \(K\).
- Order the vertices so that
\[ Q(x_1)\leq Q(x_2)\leq\cdots\leq Q(x_{p+1}), \qquad \bar{x}=\frac{1}{p}\sum_{i=1}^p x_i. \]
- With \((\alpha,\gamma,\rho,\sigma)=(1,2,1/2,1/2)\), form
\[ \begin{aligned} x_r&=\bar{x}+\alpha(\bar{x}-x_{p+1}),\\ x_e&=\bar{x}+\gamma(x_r-\bar{x}),\\ x_c^{\mathrm{out}}&=\bar{x}+\rho(x_r-\bar{x}),\\ x_c^{\mathrm{in}}&=\bar{x}+\rho(x_{p+1}-\bar{x}). \end{aligned} \]
- If \(Q(x_1)\leq Q(x_r)<Q(x_p)\), replace \(x_{p+1}\) by \(x_r\).
- If \(Q(x_r)<Q(x_1)\), replace \(x_{p+1}\) by the lower-objective point among \(x_r\) and \(x_e\).
- If \(Q(x_p)\leq Q(x_r)<Q(x_{p+1})\), replace \(x_{p+1}\) by \(x_c^{\mathrm{out}}\) only when \(Q(x_c^{\mathrm{out}})\leq Q(x_r)\).
- If \(Q(x_r)\geq Q(x_{p+1})\), replace \(x_{p+1}\) by \(x_c^{\mathrm{in}}\) only when \(Q(x_c^{\mathrm{in}})<Q(x_{p+1})\).
- If the applicable contraction condition fails, shrink:
\[ x_i\leftarrow x_1+\sigma(x_i-x_1), \qquad i=2,\ldots,p+1. \]
- Stop when both
\[ \max_i\lVert x_i-x_1\rVert_\infty\leq\varepsilon_x, \qquad \max_i\left|Q(x_i)-Q(x_1)\right|\leq\varepsilon_Q. \]
- Output: The approximate minimizer, objective value, iteration count, and solver status.
- Example problem: minimize the same Gaussian objective from \((\mu_0,\eta_0)=(0,0)\):
\[ \min_{(\mu,\eta)\in\mathbb{R}^2}Q(\mu,\eta). \]
[ Info: Saved animation to /var/folders/gc/pc_l42xd6gsbb4whn77v4x2h0000gn/T/jl_kzsnAhUzYZ.gif
nelder_mead_result = Optim.optimize(
normal_negative_log_likelihood,
initial_parameters,
Optim.NelderMead(),
)
nelder_mead_solution = Optim.minimizer(nelder_mead_result)
@show nelder_mead_solutionnelder_mead_solution = [1.4236164118327652, -0.14530934532284384]
2-element Vector{Float64}:
1.4236164118327652
-0.14530934532284384
Choosing a method
Suggested starting point
- The tree summarizes the choice after the methods above have been introduced.
%%{init: {"themeVariables": {"fontSize": "20px"}, "flowchart": {"nodeSpacing": 30, "rankSpacing": 35}}}%%
flowchart LR
A["Minimize Q(theta)"] --> B(["One dimension?"])
B -->|Yes| C(["Derivative available?"])
C -->|Yes| D["Newton"]
C -->|No| E["Golden-section search"]
B -->|No| F(["Gradient available?"])
F -->|Yes| G(["Large parameter vector?"])
G -->|Yes| H["L-BFGS"]
G -->|No| I["BFGS or Newton"]
F -->|No| J(["Local search?"])
J -->|Yes| K["Nelder--Mead"]
J -->|No| L["Global optimization"]
Benefits and costs
| Method | Benefits | Costs |
|---|---|---|
| Newton–Raphson | Fast near the optimum; uses curvature directly | Requires a Hessian |
| BFGS | Reliable default without a direct Hessian | Uses quadratic memory; depends on scaling |
| L-BFGS | Uses little memory in large problems | Retains less curvature information |
| Golden-section search | Derivative-free and evaluation-efficient | Limited to bounded, unimodal scalar problems |
| Nelder–Mead | Simple and derivative-free | Scales poorly with dimension |
Constrained optimization
- A constrained problem takes the form:
\[ \begin{aligned} \min_x \quad & f(x) \\ \text{subject to}\quad & g_j(x)=0, \\ & h_\ell(x)\leq 0. \end{aligned} \]
- The Karush–Kuhn–Tucker conditions combine:
- stationarity;
- feasibility; and
- complementary slackness.
- These conditions connect constrained optimization to systems of equations and complementarity problems.
Modeling Language: JuMP
- Unconstrained methods operate directly on an objective. Once constraints are added, JuMP provides a common way to state the full problem before choosing a compatible solver.
- Overview: JuMP is a modeling language that represents an optimization problem separately from the numerical solver.
- Idea: Express variables, objectives, and constraints in mathematical form, then pass the resulting model to a compatible solver.
- Benefits:
- The model stays separate from the solver.
- It can provide solver status, values, and dual information.
- Costs:
- You still need to choose the right solver.
- You still need to check convergence and feasibility.
- Model: Declare the variables, objective, and constraints.
- Solver: Choose a solver that matches the mathematical structure of the problem.
- Solve: Call
optimize!and record the termination status. - Verify: Check primal feasibility and the objective value before using the solution.
- Interpret: Inspect active constraints, dual values, and complementary slackness when they have an economic interpretation.
Example: JuMP grammar
using JuMP
model = Model(Solver.Optimizer)
@variable(model, x >= 0)
@objective(model, Min, objective_expression)
@constraint(model, constraint_expression <= 0)
optimize!(model)Solvers: HiGHS and Ipopt
- HiGHS and Ipopt are the two best starting points for this course because they cover the main constrained problem classes while using the same JuMP model interface.
| Solver | Use it for | Benefits | Costs |
|---|---|---|---|
| HiGHS | Linear, mixed-integer linear, and convex quadratic problems | Fast open-source solver for structured problems | Does not solve general nonlinear problems |
| Ipopt | Smooth nonlinear objectives and constraints | Uses first and second derivatives efficiently in large smooth problems | Usually returns a local solution for nonconvex problems |
Example 1: Linear Programming
- A firm chooses two outputs.
- Product 1 earns 3 units.
- Product 2 earns 5 units.
- Two resource constraints limit production.
\[ \begin{aligned} \max_{x_1,x_2\geq 0}\quad &3x_1+5x_2\\ \text{subject to}\quad &2x_1+x_2\leq 100,\\ &x_1+3x_2\leq 90. \end{aligned} \]
using JuMP
using HiGHS
production_model = Model(HiGHS.Optimizer)
set_silent(production_model)
@variable(production_model, output_1 >= 0)
@variable(production_model, output_2 >= 0)
@objective(production_model, Max, 3output_1 + 5output_2)
@constraint(production_model, 2output_1 + output_2 <= 100)
@constraint(production_model, output_1 + 3output_2 <= 90)
optimize!(production_model)
production_status = termination_status(production_model)
production_output = value.([output_1, output_2])
production_profit = objective_value(production_model)
@show production_status production_output production_profitproduction_status = MathOptInterface.OPTIMAL
production_output = [42.0, 16.0]
production_profit = 206.0
206.0
- For a linear program:
- inspect the solver status; and
- use dual values to interpret binding constraints.
Example 2: Utility Maximization Problem
- A consumer chooses two goods under a budget constraint.
- Concave quadratic utility keeps the example within the class of quadratic programs.
\[ \begin{aligned} \max_{x_1,x_2\geq 0}\quad &8x_1+6x_2-\frac{1}{2}x_1^2-\frac{1}{2}x_2^2\\ \text{subject to}\quad &2x_1+x_2\leq 10. \end{aligned} \]
consumer_model = Model(HiGHS.Optimizer)
set_silent(consumer_model)
@variable(consumer_model, good_1 >= 0)
@variable(consumer_model, good_2 >= 0)
@objective(
consumer_model,
Max,
8good_1 + 6good_2 - 0.5good_1^2 - 0.5good_2^2,
)
@constraint(consumer_model, budget, 2good_1 + good_2 <= 10)
optimize!(consumer_model)
consumer_status = termination_status(consumer_model)
consumer_consumption = value.([good_1, good_2])
consumer_utility = objective_value(consumer_model)
consumer_budget_shadow_price = shadow_price(budget)
@show consumer_status consumer_consumption consumer_utility consumer_budget_shadow_priceconsumer_status = MathOptInterface.OPTIMAL
consumer_consumption = [3.200000079999992, 3.5999998400000157]
consumer_utility = 35.59999999999999
consumer_budget_shadow_price = 2.3999998
2.3999998
- Nonlinear utility functions such as Cobb–Douglas utility can be modeled with JuMP and solved with Ipopt.
Global Optimization
- A single local optimization run can stop at a local minimum determined by its starting value.
- The methods below increase exploration in three steps: repeated local runs, deterministic partitioning of a bounded domain, and population-based search.
Multi-start local optimization
- A local solver is fast once it reaches a promising region. Multi-start retains that solver but runs it from many initial values.
- Overview: Multi-start repeats local optimization and keeps the solution with the smallest objective value.
- Idea: For initial values \(\theta_0^{(1)},\ldots,\theta_0^{(M)}\), compute
\[ \widehat{\theta}^{(m)} = \operatorname{LocalOptimize}\left(Q,\theta_0^{(m)}\right), \qquad \widehat{\theta} = \arg\min_{\widehat{\theta}^{(m)}} Q\left(\widehat{\theta}^{(m)}\right). \]
- Benefits:
- It reuses a local solver that is already available.
- The runs are independent and can be parallelized.
- Costs:
- It can miss regions not covered by the initial values.
- The total cost grows with the number of starts.
- Example problem: minimize the bounded Rastrigin function:
\[ \min_{x\in[-5,5]^2} Q(x) = 20+\sum_{j=1}^2 \left[ x_j^2-10\cos(2\pi x_j) \right]. \]
rastrigin_objective(x) =
20 + sum(value -> value^2 - 10cos(2pi * value), x)
global_lower_bounds = fill(-5.0, 2)
global_upper_bounds = fill(5.0, 2)
multistart_rng = MersenneTwister(3)
multistart_initial_values = [
global_lower_bounds +
(global_upper_bounds - global_lower_bounds) .* rand(multistart_rng, 2)
for _ in 1:20
]
multistart_results = [
Optim.optimize(
rastrigin_objective,
global_lower_bounds,
global_upper_bounds,
initial_value,
Optim.Fminbox(Optim.LBFGS());
autodiff = :forward,
)
for initial_value in multistart_initial_values
]
multistart_objectives = Optim.minimum.(multistart_results)
multistart_best_index = argmin(multistart_objectives)
multistart_best_solution =
Optim.minimizer(multistart_results[multistart_best_index])
multistart_best_objective =
multistart_objectives[multistart_best_index]
@show multistart_best_solution multistart_best_objectivemultistart_best_solution = [2.4984163221551648e-20, 8.723808631502222e-20]
multistart_best_objective = 0.0
0.0
NLopt.jl
- Multi-start chooses the search regions through its initial values. NLopt also provides algorithms that construct their own search regions.
- Overview: NLopt provides one interface to many local and global algorithms.
- Idea:
- DIRECT (
GN_DIRECT_L): partitions a bounded domain into rectangles, evaluates their centers, and refines rectangles that balance a low objective value with further exploration. - COBYLA (
LN_COBYLA): builds linear approximations to the objective and constraints from a simplex, then optimizes them inside a trust region. COBYLA is a local constrained method, not a global optimizer.
- DIRECT (
- Benefits:
- Both methods work without derivatives.
- The algorithm name records whether the method is global or local and whether it uses derivatives.
- Costs:
- DIRECT requires finite bounds and becomes expensive as dimension grows.
- COBYLA does not provide a global-optimum guarantee.
- Package example: use DIRECT on the Rastrigin problem:
using NLopt
direct_optimizer = NLopt.Opt(:GN_DIRECT_L, 2)
NLopt.lower_bounds!(direct_optimizer, [-5.0, -5.0])
NLopt.upper_bounds!(direct_optimizer, [5.0, 5.0])
NLopt.min_objective!(
direct_optimizer,
(x, gradient) -> rastrigin_objective(x),
)
NLopt.maxeval!(direct_optimizer, 5_000)
direct_minimum, direct_solution, direct_status =
NLopt.optimize(direct_optimizer, zeros(2))
@show direct_solution direct_minimum direct_statusDifferential Evolution
- DIRECT explicitly subdivides the domain. Differential Evolution instead uses differences between population members to determine the scale and direction of new trials.
- Overview: Differential Evolution is a population-based, derivative-free global optimization method.
- Idea: Construct trial points from scaled differences between population members, then apply crossover and selection.
- Benefits:
- It does not need derivatives.
- The population explores several regions at once.
- Costs:
- It often needs many function evaluations.
- Standard DE uses fixed mutation and crossover parameters, which may work differently across objectives and stages of the search.
- The figure follows the four-step intuition in LeftLetter (2019): initialize the population, construct a trial, select the better point, and repeat.
- Input: A bounded objective \(Q\), a population, a mutation scale \(F\), a crossover probability \(C_R\), and a maximum generation count.
- For each target \(x_i^{(t)}\), choose distinct indices \(r_1,r_2,r_3\neq i\) and construct the mutant:
\[ v_i^{(t)} = x_{r_1}^{(t)} +F\left(x_{r_2}^{(t)}-x_{r_3}^{(t)}\right). \]
- For a random coordinate \(j_{\mathrm{rand}}\), form the trial point:
\[ u_{ij}^{(t)} = \begin{cases} v_{ij}^{(t)}, & r_{ij}\leq C_R \ \text{or}\ j=j_{\mathrm{rand}},\\ x_{ij}^{(t)}, & \text{otherwise}, \end{cases} \qquad r_{ij}\sim U(0,1). \]
- Apply one-to-one selection:
\[ x_i^{(t+1)} = \begin{cases} u_i^{(t)}, & Q(u_i^{(t)})\leq Q(x_i^{(t)}),\\ x_i^{(t)}, & \text{otherwise}. \end{cases} \]
- Stop at the generation or evaluation budget and return the population member with the smallest objective value.
- Output: The approximate global minimizer, objective value, evaluation count, and solver status.
- Example problem: minimize the same bounded Rastrigin function.
SHADE
Problem with standard DE: fixed \(F\) and \(C_R\) can be sensitive to the objective and to the current search stage.
Idea: SHADE records successful values of \(F\) and \(C_R\), samples future values from that history, and uses a p-best mutation with an archive to preserve diversity.
SHADE therefore changes how the mutation and crossover parameters are chosen; the trial construction and one-to-one selection still follow the DE logic.
Package example: the DifferentialEvolution.jl package provides both
:deand:shade:
import DifferentialEvolution
using Random
de_result = DifferentialEvolution.optimize(
rastrigin_objective,
[-5.0, -5.0],
[5.0, 5.0];
rng = MersenneTwister(42),
algorithm = :de,
maxiters = 200,
)
shade_result = DifferentialEvolution.optimize(
rastrigin_objective,
[-5.0, -5.0],
[5.0, 5.0];
rng = MersenneTwister(42),
algorithm = :shade,
maxiters = 200,
)
@show de_result.best_x de_result.best_f
@show shade_result.best_x shade_result.best_f- DE is a useful and effective method. This Julia package is my implementation, but I have not been able to develop it actively recently.
- Comments and pull requests are welcome.
Reference
- Miranda, M. J., and Fackler, P. L. (2002), Applied Computational Economics and Finance.
- Judd, K. L., Numerical Methods in Economics, Lectures 4–7.
- Train, K. E. (2009), Discrete Choice Methods with Simulation, Chapter 8.
- Storn, R., and Price, K. (1997), Differential Evolution: A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces.
- Tanabe, R., and Fukunaga, A. (2013), Evaluating the Performance of SHADE on CEC 2013 Benchmark Problems.
- Shimamoto, K., DifferentialEvolution.jl.