Count the numerical rank of a matrix from its singular values
Floating point makes exact rank useless: a rank 2 matrix built from data will have tiny but nonzero extra singular values.
Write numerical_rank(X, rtol=1e-10). Compute the singular values s and count how many are greater than rtol * s.max(). A zero matrix has rank 0.
def numerical_rank(X, rtol=1e-10)Example
numerical_rank([[1, 2], [2, 4]]) is 1.
Understand the idea
In exact maths, rank counts independent rows. With floating point numbers, a matrix that should have rank 2 often shows a tiny third singular value like 5e-16 that is just rounding noise. Numerical rank counts only singular values that are large compared with the biggest one. Worked example: X = [[1, 2, 3], [2, 4, 6], [1, 0, 1]]. Row 2 is twice row 1, so the true rank is 2. The singular values come out about [8.435, 0.918, 5.3e-16]. The cutoff is 1e-10 * 8.435 = 8.4e-10, so two values pass and the numerical rank is 2. Counting everything above zero would wrongly say 3. Rule: compute the singular values s; rank = number of s greater than rtol * max(s); a zero matrix (max 0) has rank 0. A relative cutoff works no matter how large or small the entries are. Used to detect redundant features, check LoRA update ranks and measure how many directions a set of embeddings really spans.