Skip to content

pymath.least_squares_box_constrained

Daniel Flassig edited this page Jul 16, 2026 · 1 revision

Solves the least-squares problem min |A . x - b| subject to per-variable box constraints lower ≤ x ≤ upper, returning the constrained solution vector x. On failure it returns nil plus a failure reason.

x = pymath.least_squares_box_constrained(A, b, constraints)
x, reason = pymath.least_squares_box_constrained(A, b, constraints)  -- on failure
Parameter Type Description
A matrix An m × n matrix (m rows, n columns), represented as an array of m row-vectors.
b vector The right-hand side, a table read as a vector of length m (missing entries read as 0).
constraints array One entry per column of A (per variable). Each entry is either nil (that variable is unconstrained) or a {lower, upper} pair. Within a pair, lower and upper may each be a number or nil; a nil bound means unbounded on that side.

Return value

Type Description
x A new vector of length n minimizing `
nil, reason On failure, nil and a string describing the cause: "rank deficient", "invalid bounds" (some lower exceeds its upper), or "iteration limit exceeded".

Notes:

  • A variable is constrained only where you supply a bound. nil entries, and nil sides of a {lower, upper} pair, leave that direction free.
  • A matrix with fewer rows than columns (m < n) cannot have full column rank, so it returns nil, "rank deficient" like any other rank-deficient case.
  • This function employs a dense direct solver

Example:

-- Fit a line y = c0 + c1*x through (0,1), (1,2), (2,2), but cap the slope at 0.3.
local A = {{1, 0},
           {1, 1},
           {1, 2}}
local b = {1, 2, 2}

-- c0 (intercept) unconstrained, c1 (slope) in [0, 0.3]:
local constraints = { nil, {0, 0.3} }
local x = pymath.least_squares_box_constrained(A, b, constraints)
-- x ≈ {1.36667, 0.3}          -- slope pinned at its upper bound

-- One-sided bound: keep the slope non-negative, no upper limit.
local x2 = pymath.least_squares_box_constrained(A, b, { nil, {0, nil} })
-- x2 ≈ {1.16667, 0.5}         -- unconstrained optimum already satisfies it

Version Support:

Minimum PYTHA Version: V27

See also:

pymath, pymath.least_squares, pymath.solve_linear

Clone this wiki locally