Compute a QR decomposition with Householder reflections
QR is how least squares is solved in practice, because it never forms X.T X and so never squares the condition number.
Write householder_qr(A) for an (m, n) array with m >= n. Use Householder reflections column by column. Return (Q, R) with Q of shape (m, m) orthogonal and R of shape (m, n) upper triangular, such that Q @ R equals A. Fix the signs so every diagonal entry of R is non-negative, which makes the answer unique for full-rank A.
def householder_qr(A)Example
householder_qr([[3], [4]]) gives R = [[5], [0]].
Understand the idea
QR writes A = Q R with Q orthogonal and R upper triangular. Householder QR builds it with mirror reflections: each reflection flips one column so everything below the diagonal becomes zero, while lengths stay the same. Worked example: A = [[3], [4]]. The column has length 5. Choose v = x + sign(x0) * 5 * e1 = [8, 4]. The reflection H = I - 2 v v^T / (v^T v) maps [3, 4] to [-5, 0]. So R = [[-5], [0]] and Q = H. The task wants non-negative diagonals, so flip the sign of that row of R and the matching column of Q: R = [[5], [0]]. Rule: for k = 0 to n - 1, take x = R[k:, k], form v as above (skip if x is already zero), apply H to rows k onward of R, and accumulate the same reflection into Q so that Q R = A always holds; at the end, wherever R[i, i] < 0, negate row i of R and column i of Q. Q is (m, m), R is (m, n). QR is how least squares is solved stably in practice.