Optimization
Find where a function is zero or smallest from a script, fit model parameters to data, and solve systems of nonlinear equations.
01Overview
What This Page Covers
Four related problems: where does one function cross zero, which input makes a function smallest, which parameters make a model fit data, and which unknowns satisfy several equations at once.
Luau reaches three of the five routines on this page: fzero, fminsearch and fminunc, six names with the _with and fzero_from forms. Rune reaches lsqnonlin and fsolve besides, marked Rune only in the table; choose Rune at the top of the page to read their script forms. Rune reaches all five routines: fzero, fminsearch, fminunc, lsqnonlin and fsolve; that is ten names in Rune. Luau reaches the first three. The Rust crate eustress-numerics has all five. The conventions shared by every routine (the Numerics tableeustress::realism::numerics module, arrays, results and errors) are on the Numerics overview.
| Problem | Routine | Method | Scripts |
|---|---|---|---|
| The zero of one function, in a bracket or near a guess | fzero | Brent's method | Luau and Rune |
| The smallest value of a function, from function values only | fminsearch | Nelder-Mead simplex | Luau and Rune |
| The smallest value of a smooth function | fminunc | BFGS with a strong-Wolfe line search | Luau and Rune |
| Model parameters that fit data | lsqnonlin | Levenberg-Marquardt | Rune only |
| A square system of nonlinear equations | fsolve | Trust-region dogleg | Rune only |
fminsearch, fminunc, lsqnonlin and fsolve are local methods: they find a minimum or a root near where they start, and a different starting point can reach a different answer.
Passing a Function
The function to minimize returns one number for a vector of inputs. A residual function (for lsqnonlin) and a system of equations (for fsolve) each return a vector of numbers for a vector of inputs. The function for fzero takes one number and returns one number. Every starting point and every function value must be finite; a non-finite value at the start is an error.
In a script the function is an ordinary functionan ordinary closure. The function for fminsearch and fminunc takes one argument, the point x as an array, and returns one number: function(x) return (x[1] - 1)^2 + (x[2] - 2)^2 end, where the array counts from 1.|x| (x[0] - 1.0) * (x[0] - 1.0) + (x[1] - 2.0) * (x[1] - 2.0), where the array counts from 0. The function for fzero takes one number and returns one number. A function that returns anything else fails the call with a message that names the routine; it reads the objective must return a number for the two minimizers and the function must return a number for fzero.
An error that your own function raises ends the call. The error that comes back carries your message. The call returns Err with a message that starts numerics::fminsearch: the callback failed: (or the name of the routine you called) followed by your message. After the first error from your function the routine does not call it again.
02Roots of One Equation
fzero
fzero finds a root of a function of one variable by Brent's method. It has two forms.
- Inside a bracket. Give an interval whose two end values have opposite signs. If an end value is exactly zero, that end is the root and no iteration runs. If both ends have the same sign, the call fails with
invalid argument: fzero: function values at the bracket ends must differ in sign. A non-finite end value fails withinvalid argument: fzero: function values at the bracket ends must be finite. - Near a starting guess. The routine widens a bracket around the guess until the sign changes, then runs Brent. The first half-width is the guess's magnitude divided by 50 (1/50 when the guess is zero), and it grows by a factor of the square root of 2 on each of up to 200 attempts. If no sign change appears, the call fails with
no convergence: fzero: no sign change found around the starting point.
The tolerance on the root defaults to machine epsilon. The search stops when the half-width of the bracket is at most 2 epsilon times the magnitude of x plus half the tolerance, or after 500 iterations. Reaching 500 iterations, or meeting a non-finite function value during the search, is an error and not a result; the messages are no convergence: fzero: iteration limit reached and no convergence: fzero: the function returned a non-finite value.
The result holds the root, the function value there, the number of iterations and the number of function evaluations. It has no converged flag, because a search that did not converge is an error.
The test suite checks fzero against SciPy brentq:
- cos x - x on [0, 1] matches SciPy's root to a relative error of 1e-15.
- x^3 - 2x - 5 on [2, 3] matches to 1e-15 and uses fewer than 15 function evaluations.
- cos x - x from the starting guess 3 matches to 1e-14.
- x^2 + 1 on [0, 1] fails with an invalid argument error, and from the starting guess 0 it fails.
A script chooses the form by the arguments. Numerics.fzero(f, a, b) searches the bracket from a to b, and Numerics.fzero(f, a) with no third argument starts from the guess a; Numerics.fzero_from(f, x0) is the guess form under its own name. There are no optional arguments: numerics::fzero(f, a, b)? is the bracket form and numerics::fzero_from(f, x0)? is the guess form. A script cannot set the tolerance, so a script call uses the defaults above: machine epsilon and 500 iterations.
The result is a tablean object with the fields x, fx, iterations and evaluations. A field is read as r["x"]. The example finds the root of x^3 - 2x - 5 in the bracket [2, 3], one of the test cases above; the root is 2.0946 to four decimals.
local r = Numerics.fzero(function(x) return x * x * x - 2 * x - 5 end, 2, 3)
print(string.format("%.4f", r.x)) -- 2.0946use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let r = numerics::fzero(|x| x * x * x - 2.0 * x - 5.0, 2.0, 3.0)?;
let root = r["x"];
log_info(`root = ${root}`); // 2.0946 to four decimals
}A failed search is an error and not a result, as described above: a bracket whose ends have the same sign, a guess with no sign change near it, and the iteration limit. A script catches it with pcall.The call returns Err.
03Minimization
Without Gradients
fminsearch minimizes a function of several variables from function values alone, by the Nelder-Mead simplex method (Lagarias and others, 1998). It builds a starting simplex of n + 1 points from your start: the start itself, and for each variable one point with that variable multiplied by 1.05 (set to 0.00025 when it is zero). It then reflects, expands, contracts and shrinks the simplex.
| Option | Default | Meaning |
|---|---|---|
| Position tolerance | 1e-4 | Largest coordinate difference between the best point and the others |
| Value tolerance | 1e-4 | Largest difference in function value between the best point and the others |
| Iteration budget | 200 times n | n is the number of variables |
| Evaluation budget | 200 times n | Function evaluations |
| Adaptive | Off | Dimension-dependent coefficients (Gao and Han, 2012) that need fewer evaluations in more than a few dimensions; MATLAB has no such switch |
The search stops, and reports converged, when both the simplex size and the function spread are within tolerance. If a budget runs out first, the call still returns its best point, with converged false. An empty start fails with invalid argument: fminsearch: x0 is empty and a non-finite start with invalid argument: fminsearch: x0 must be finite.
The test suite checks fminsearch on the two-variable Rosenbrock function from (-1.2, 1) against SciPy Nelder-Mead with both tolerances at 1e-10 and budgets of 10000: it converges, the minimizer agrees to 1e-8 and the value is below 1e-18. The same test also runs the six-variable Rosenbrock function with a limit of 50 iterations and checks that converged is false.
The call is Numerics.fminsearch(f, x0, opts), with the options table optional. The call is numerics::fminsearch(f, x0)? with the defaults and numerics::fminsearch_with(f, x0, opts)? with options. The start x0 is an array. The options are named tol_x (position tolerance), tol_fun (value tolerance), max_iter and max_fun_evals (the two budgets, whole numbers) and adaptive (true or false). The result has the fields x (an array), fval, iterations, evaluations and converged (true or false); a script checks converged before it trusts the point.
local f = function(x) return (x[1] - 1)^2 + (x[2] - 2)^2 end
local r = Numerics.fminsearch(f, {0, 0}, {tol_x = 1e-8, tol_fun = 1e-8})
if r.converged then print(r.x[1], r.x[2], r.fval) enduse eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let r = numerics::fminsearch_with(
|x| (x[0] - 1.0) * (x[0] - 1.0) + (x[1] - 2.0) * (x[1] - 2.0),
[0.0, 0.0],
#{tol_x: 1e-8, tol_fun: 1e-8},
)?;
let done = r["converged"];
log_info(`converged = ${done}`);
}In the library run, with the default options, fminsearch converged after 84 iterations and 159 function evaluations. It stopped at (1.000022, 1.000042) with a value of 8.2e-10. A second form of the routine also returns the best point after every iteration, which is what the figure draws: row 0 is the best vertex of the starting simplex, (-1.2, 1.05).
With Gradients: BFGS
fminunc minimizes a smooth function by the quasi-Newton BFGS method with a strong-Wolfe line search (constants c1 = 1e-4 and c2 = 0.9). It has two forms: you supply a function that returns the value and the gradient, or you supply the value alone and the routine estimates each gradient component by central differences. It has no trust-region variant.
| Option | Default | Meaning |
|---|---|---|
| Gradient tolerance | 1e-6 | Stop when the largest gradient component is below this |
| Step tolerance | 1e-12 | Stop when the step and the change in value are both below this scale |
| Iteration budget | 400 | Running out returns the best point with converged false |
When a step direction is not a descent direction, the routine restarts from steepest descent. An empty start fails with invalid argument: fminunc: x0 is empty, and a value or gradient that is not finite at the start fails with invalid argument: fminunc: objective or gradient is not finite at x0. With a supplied gradient the result counts each value-and-gradient call in both the evaluation count and the gradient count; with central differences it counts every function call in the evaluation count and reports a gradient count of 0.
The test suite runs the ten-variable Rosenbrock function from the alternating start (-1.2, 1, -1.2, ...) with an analytic gradient and a gradient tolerance of 1e-8: it converges and every gradient component is at most 1e-8. That function has a second local minimum near x1 = -1 with a value of about 3.99, so a local method may land on either minimum; the test accepts the global one or SciPy's. With central differences the two-variable Rosenbrock function from (-1.2, 1) reaches (1, 1) to 1e-6.
A script cannot pass a gradient. The value-only form is the one scripts call, so the routine estimates each gradient component by central differences; the form with a supplied gradient is part of the Rust crate. The call is Numerics.fminunc(f, x0, opts), with the options table optional. numerics::fminunc(f, x0)? or numerics::fminunc_with(f, x0, opts)?. The function and the start are the same as for fminsearch. The options are tol_grad (gradient tolerance), tol_x (step tolerance) and max_iter (the iteration budget, a whole number).
The result has the fields x, fval, iterations, evaluations and converged, spelled the same way as for fminsearch. The gradient-evaluation count is not returned to a script.
Choosing Between Them
- fminsearch needs only function values, so it works when you cannot write a gradient. Its default budget of 200 times n iterations can end the search early; check converged.
- fminunc uses gradient information, supplied or estimated, and tests convergence on the gradient. It suits smooth functions, and a gradient you can write exactly saves the evaluations that central differences spend.
- Either finds a local minimum. For a function with several minima, try more than one starting point.
Which minimum a local method reaches depends on the start. The ten-variable Rosenbrock function from the alternating start (-1.2, 1, -1.2, 1, ...) shows it, with both tolerances at 1e-8 and a budget of 100000 iterations and evaluations. The library's adaptive Nelder-Mead stops in the local minimum, with a value of about 3.99, where SciPy's adaptive Nelder-Mead reaches the global one (8.0e-17). With the standard coefficients and in BFGS with an analytic gradient it is the other way round: the library reaches the global minimum (1.7e-16 and 4.1e-22) and SciPy stops at 3.99. The adaptive result is a property of this start and not a defect in the routine.
The measured evaluation counts for the ten-variable Rosenbrock problem are on the Performance page.
04Nonlinear Least Squares
lsqnonlin
lsqnonlin minimizes the sum of squares of a vector of residuals by the Levenberg-Marquardt method. The result's value is that sum of squares. You can supply the Jacobian of the residuals (an m-by-n matrix for m residuals and n parameters); otherwise the routine estimates it by forward differences. Bounds on the parameters are not supported.
| Option | Default | Meaning |
|---|---|---|
| Gradient tolerance | 1e-10 | Largest component of the gradient (the Jacobian transpose times the residuals) |
| Step tolerance | 1e-12 | Relative size of the step |
| Function tolerance | 1e-24 | Stop when the sum of squares is below this |
| Iteration budget | 400 | Running out returns the best point with converged false |
The routine fails with invalid argument: lsqnonlin: x0 is empty, with invalid argument: lsqnonlin: residuals must be a non-empty finite vector at x0 when the residual vector is empty or not finite at the start, and with invalid argument: lsqnonlin: the Jacobian has the wrong shape when a supplied Jacobian is not m by n.
Rune calls numerics::lsqnonlin(r, x0)? and numerics::lsqnonlin_with(r, x0, opts)?. The residual function is |x| [..] and returns an array with one value per residual; x0 is the start array. The options object takes tol_grad, tol_x, tol_fun and max_iter, with the defaults in the table above, and jacobian, a function |x| J that returns the m-by-n matrix of partial derivatives as an array of rows; a matrix of another size fails the call. The result is an object with the fields x, fval (the sum of squares), iterations, evaluations, jacobian_evaluations and converged, read as r["x"]. Without a jacobian option jacobian_evaluations is 0.
Luau does not reach lsqnonlin; a Luau script that needs a fit can minimize the sum of squares of the residuals itself with fminsearch or fminunc, which take a function of the parameter array and return one number.
Example: Fitting a Model to Data
The library's test fits the model p0 exp(-p1 t) + p2 to 20 data points. The points lie at times evenly spaced from 0 to 4, generated from the parameters (2.5, 1.3, 0.5) plus noise with a standard deviation of 0.01. The residual for each point is the model minus the data value. The start is (1, 1, 0).
The test compares the fit with SciPy least_squares using its Levenberg-Marquardt method at tolerances of 1e-14. The fitted parameters agree to 1e-7, and the sum of squares agrees to a relative error of 1e-8. With the analytic Jacobian, the parameters agree to 1e-9.
In the library run, the fit started at (1, 1, 0) with a forward-difference Jacobian and converged in 14 iterations and 42 function evaluations. The fitted parameters are a = 2.4910, b = 1.2978 and c = 0.5038, close to the (2.5, 1.3, 0.5) that generated the data, and the sum of squares is 1.884e-3. This fit runs through the Rust crate; the Rune example below fits a smaller model through lsqnonlin.
Luau does not reach lsqnonlin, so it has no example of this fit.
The Rune example fits the model a (1 + b t) to three points: (0, 2), (1, 8) and (2, 14). The data come from a = 2 and b = 3, so the residuals vanish there and the fitted parameters are close to 2 and 3. The three residuals are written out, one per point, and the start is (1, 1).
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let residuals = |p| [p[0] - 2.0, p[0] * (1.0 + p[1]) - 8.0, p[0] * (1.0 + 2.0 * p[1]) - 14.0];
let fit = numerics::lsqnonlin(residuals, [1.0, 1.0])?;
let params = fit["x"];
let ok = fit["converged"];
log_info(`a, b = ${params[0]}, ${params[1]}`); // close to 2 and 3
log_info(`converged = ${ok}`);
}05Systems of Nonlinear Equations
fsolve
fsolve solves a square system F(x) = 0, with as many equations as unknowns, by Powell's trust-region dogleg method. A system that is not square fails with invalid argument: fsolve: the system must be square (as many equations as unknowns). A starting value where F is not finite fails with invalid argument: fsolve: F(x0) is not finite.
You can supply the Jacobian (an n-by-n matrix); otherwise it is estimated by forward differences. It shares its options with lsqnonlin and uses three of them: step tolerance 1e-12, function tolerance 1e-24 on the sum of squares, and 400 iterations. Its search never tests the gradient tolerance. When the Jacobian is singular, the Newton step falls back to the minimum-norm least-squares solution of the linearized system, so a singular Jacobian does not stop the iteration on its own.
A root is reported when the sum of squares of F falls within the function tolerance, or when the residual norm is at most 1e-9 times one plus the largest magnitude in x. Any other end is an error, never a result: if the iteration stalls, or the iteration budget runs out, the call fails with no convergence: fsolve: stalled with residual norm .... The reason is that a point that is not a root is not a usable answer.
The test suite solves x^2 + y^2 = 4 together with e^x + y = 1 from (1, -1). The root agrees with SciPy's hybr to 1e-10 and the residual norm is below 1e-12. The single equation x^2 + 1 = 0 has no real root, and the call fails with a no convergence error.
Rune calls numerics::fsolve(f, x0)? and numerics::fsolve_with(f, x0, opts)?. The system function is |x| [..] and returns an array with one value per equation. The options and the result are those of lsqnonlin: tol_grad, tol_x, tol_fun, max_iter and jacobian (here an n-by-n matrix), and the fields x, fval, iterations, evaluations, jacobian_evaluations and converged.
Luau does not reach fsolve; for one equation in one unknown a Luau script calls fzero.
The Rune example solves x^2 + y^2 = 25 together with x - y = 1 from the start (3, 2). By hand the roots are (4, 3) and (-3, -4); the start lies next to the first, so the solver reaches (4, 3), and x is close to that point.
use eustress::log_info;
use eustress::realism::numerics;
pub fn on_init() {
let system = |p| [p[0] * p[0] + p[1] * p[1] - 25.0, p[0] - p[1] - 1.0];
let sol = numerics::fsolve(system, [3.0, 2.0])?;
let root = sol["x"];
log_info(`root = ${root[0]}, ${root[1]}`); // close to 4 and 3
}06Options and Exit Reports
Tolerances and Limits
| Routine | Defaults | Stops when |
|---|---|---|
fzero | Position tolerance machine epsilon; 500 iterations | The bracket half-width is at most 2 epsilon |x| plus half the tolerance |
fminsearch | Both tolerances 1e-4; 200 n iterations and evaluations | Both the simplex size and the function spread are within tolerance |
fminunc | Gradient tolerance 1e-6; 400 iterations; strong-Wolfe search (c1 1e-4, c2 0.9) | The largest gradient component is below the tolerance |
lsqnonlin, fsolve | Gradient 1e-10 (lsqnonlin only), step 1e-12, function 1e-24; 400 iterations | The gradient (lsqnonlin only) or the step is below its tolerance, or the residual vanishes |
A script passes options as a tablean object with these names, and only for the routines its language reaches:
| Routine | Option names |
|---|---|
fzero, fzero_from | None: a script call uses the defaults |
fminsearch | tol_x, tol_fun, max_iter, max_fun_evals, adaptive |
fminunc | tol_grad, tol_x, max_iter |
lsqnonlin, fsolve (Rune only) | tol_grad, tol_x, tol_fun, max_iter, jacobian |
The table {tol_x = 1e-8, max_iter = 500} goes last in the call. The object #{tol_x: 1e-8, max_iter: 500} goes last in the _with form. A name that a routine does not know is an error that lists the valid names. A budget option must be a whole number from 0 up. Only Rune reaches lsqnonlin and fsolve.
Reading the Result
The routines report an exhausted budget in two different ways, and a script has to check the right one.
- fminsearch, fminunc and lsqnonlin return a result with converged false when they run out of budget. The point is the best one found and may be a useful answer.
- fzero and fsolve return an error instead, because a point that is not a root is not a usable answer.
The two result types carry these fields:
| Result | Field | Meaning |
|---|---|---|
| Minimization and least squares | x | The best point found |
fval | The objective value there; for lsqnonlin and fsolve, the sum of squares | |
iterations | Iterations used | |
evaluations | Objective evaluations used, finite-difference evaluations included | |
gradient_evaluations | Gradient or Jacobian evaluations that you supplied | |
converged | True when a convergence test was met, false when a budget ran out | |
| Scalar root | x, fx | The root and the function value there |
iterations, evaluations | Work used |
fsolve returns the minimization result type, and its converged field is always true on success. A call cannot be cancelled from outside and reports no progress, so set the iteration limits to bound the work.
A script reads the fields by name: r.x, r.fval, r.iterations, r.evaluations and r.converged for fminsearch and fminunc, and r.x, r.fx, r.iterations and r.evaluations for fzero and fzero_fromr["x"], r["fval"], r["iterations"], r["evaluations"] and r["converged"] for fminsearch and fminunc, and r["x"], r["fx"], r["iterations"] and r["evaluations"] for fzero and fzero_from. In the minimizers x is an array; in the root finders it is a number. Luau does not reach lsqnonlin or fsolve. For lsqnonlin and fsolve, fval is the sum of squares and the count of supplied Jacobian calls is jacobian_evaluations. The gradient_evaluations count of fminsearch and fminunc is not returned to a script.
Before a script trusts a minimizer's point, it checks converged; a false value means a budget ran out and the point is the best one found. A script that calls fzero has no flag to check, because every failure is an error: wrap the call in pcalllet ? turn the Err into a script error or match on it.
07What Is Not Covered
Missing Routines and Alternatives
These MATLAB routines are not in the library. Where the table gives an alternative, it is the nearest one.
| Not covered | Use instead |
|---|---|
fminbnd | fzero on the derivative, or fminsearch in one variable |
fmincon, and bounds in lsqnonlin | A penalty term or a change of variables, then fminunc or lsqnonlin |
lsqcurvefit | lsqnonlin on the model value minus the data value (Rune and the Rust crate); in Luau, fminsearch or fminunc on the sum of squares |
linprog, quadprog, ga | No equivalent |
particleswarm, patternsearch | fminsearch from several starting points, keeping the best result |
08What's Next
Where to Go from Here
Differential Equations notes that a boundary-value problem can be shot with ode45 inside fsolve in Rune or in the Rust crate. Calculus and Signal covers integration, interpolation and filtering of sampled data.
Control Design covers transfer-function and state-space models and controller design, and Performance holds the measured evaluation counts.