Skip to content

pymath.least_squares

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

Solves the least-squares problem min |A . x - b|, returning the solution vector x that minimizes the residual, or nil if A is (close to) rank-deficient.

x = pymath.least_squares(A, b)
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).

Return value

Type Description
x A new vector of length n minimizing `

Notes:

  • For a square A (m == n) this function also calculates the solution of A . x == b. But prefer pymath.solve_linear in this case
  • A matrix with fewer rows than columns (m < n) cannot have full column rank, so it returns nil like any other rank-deficient case.
  • This function employs a dense direct solver

Example:

-- Fit a line y = c0 + c1*x through the points (0,1), (1,2), (2,2).
local A = {{1, 0},
           {1, 1},
           {1, 2}}
local b = {1, 2, 2}
local x = pymath.least_squares(A, b)
-- x ≈ {1.16667, 0.5}          -- intercept c0, slope c1

local R = {{1, 2},
           {2, 4},
           {3, 6}}              -- columns are linearly dependent
local xr = pymath.least_squares(R, {1, 1, 1})
-- xr == nil                    -- rank-deficient

Version Support:

Minimum PYTHA Version: V27

See also:

pymath, pymath.least_squares_box_constrained, pymath.solve_linear, pymath.inverse

Clone this wiki locally