Topic

Orthogonality and least squares

Gram–Schmidt without square roots

Gram–Schmidt makes a set of vectors perpendicular by subtracting from each its projections onto the earlier ones: q = a − Σ (a·qₖ)/(qₖ·qₖ) qₖ. Projections need no square roots, so if you skip the final normalization everything stays rational. The library's exact QR is this form: A = QR with Q's columns orthogonal and R unit upper triangular, plus the squared lengths. Dividing by their square roots gives the usual orthonormal QR, which is what the float preview shows.

Least squares

When there are more equations than unknowns, A·x = b usually has no solution. The best x makes the error b − A·x as short as possible, which happens when the error is perpendicular to every column of A: AᵀA·x = Aᵀb. For rational data the answer is rational, so the library returns it exactly, along with the residual.

The pseudoinverse

A⁺ gives the least-squares solution of least length for any A, even when columns depend on each other. For a rational matrix it is rational: with A = C·F a full-rank factorization (C the pivot columns, F the nonzero rows of the reduced form), A⁺ = Fᵀ(FFᵀ)⁻¹(CᵀC)⁻¹Cᵀ.

Singular values

The singular values are the square roots of the eigenvalues of AᵀA. The library isolates the eigenvalues of the smaller of AᵀA and AAᵀ exactly, then maps each isolating interval through the square root, so each singular value is an exact algebraic number. U and V are irrational in general and are given in floating point.

In code

import { leastSquares, qr, pseudoinverse, singularValues } from "@ratmath/linalg";

const A = [[1, 1], [1, 2], [1, 3]];
const ls = leastSquares(A, [1, 2, 2]).exact();
ls.x.toStrings();          // [["2/3"], ["1/2"]]: the line 2/3 + x/2
ls.residual.toStrings();   // [["-1/6"], ["1/3"], ["-1/6"]]

const q = qr(A).exact();
q.Q.toStrings();           // [["1","-1"], ["1","0"], ["1","1"]], orthogonal columns
q.normsSquared;            // 3 and 2, their squared lengths

pseudoinverse(A).exact().toStrings();   // [["4/3","1/3","-2/3"], ["-1/2","0","1/2"]]
singularValues(A).exact().map((s) => s.value.toString(10));
// ["4.0791433289…", "0.6004912172…"]
Try itEdit the code and run it with @ratmath/linalg and Core's Rational, RationalInterval in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs