Compute a matrix's 2-norm condition number from its singular values

Why it matters Condition numbers explain why normal equations fail on collinear features, why ridge regularisation helps, and when a solver's answer cannot be trusted.

The condition number tells you how much a linear solve can amplify errors in the input. Large values mean the matrix is close to singular.

Write condition_number(A). A is any 2D matrix. Compute its singular values with np.linalg.svd. Return s_max / s_min as a float, or float('inf') if s_min <= 1e-12 * s_max (numerically singular) or the matrix is all zeros.

Signaturedef condition_number(A)

Example

A [[1, 0], [0, 0.01]] gives 100.0.

Understand the idea

A matrix stretches some directions more than others. The singular values are those stretch factors. If one direction is stretched by 1 and another by only 0.01, then solving A x = b means dividing by 0.01 in that direction, so a small error in b becomes 100 times bigger in x.

Worked example: A = [[1, 0], [0, 0.01]] has singular values 1 and 0.01, so the condition number is 1 / 0.01 = 100. You can lose about two digits of accuracy (log10 of 100) when solving with it.

A trap: for non-symmetric matrices eigenvalues can mislead. [[1, 100], [0, 1]] has both eigenvalues equal to 1, yet it shears space so strongly that its singular values are about 100 and 0.01, giving a condition number near 10,000.

Rule: cond(A) = s_max / s_min, infinite if s_min is effectively 0.

In ML, X^T X for highly correlated features has a huge condition number, which is exactly why ridge regression (adding lam I) or a QR/SVD solver is preferred over the plain normal equation.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: examplecondition_number([[1, 0], [0, 0.01]])
  • Sample 2: non-normalcondition_number([[1, 100], [0, 1]])
  • Test 3: singularcondition_number([[1, 2], [2, 4]]) == float('inf')
  • Test 4: rectangularcondition_number([[1, 0], [0, 2], [0, 0]])
  • Test 5: orthogonalcondition_number([[0, 1], [-1, 0]])