← back

Calculate Eigenvalues of a Matrix

#6 · Linear Algebra · Medium

⊣ Solve on deep-ml.com

Problem

Calculate the eigenvalues of a 2x2 matrix. The eigenvalues are the roots of the characteristic polynomial det(A - lambda * I) = 0.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def calculate_eigenvalues(matrix: list[list[float]]) -> list[float]:
    a, b = matrix[0]
    c, d = matrix[1]
    # Characteristic equation: lambda^2 - (a+d)*lambda + (ad - bc) = 0
    trace = a + d
    det = a * d - b * c
    discriminant = trace ** 2 - 4 * det
    if discriminant >= 0:
        sqrt_disc = discriminant ** 0.5
        e1 = (trace + sqrt_disc) / 2
        e2 = (trace - sqrt_disc) / 2
    else:
        # Complex eigenvalues - return real and imaginary parts
        sqrt_disc = (-discriminant) ** 0.5
        e1 = complex(trace / 2, sqrt_disc / 2)
        e2 = complex(trace / 2, -sqrt_disc / 2)
    return [e1, e2]

Explanation

  1. Extract elements a, b, c, d from the 2x2 matrix.
  2. The characteristic polynomial is lambda^2 - trace*lambda + det = 0, where trace = a + d and det = ad - bc.
  3. Apply the quadratic formula to find the two eigenvalues.
  4. Handle the case where the discriminant is negative (complex eigenvalues).

Complexity

  • Time: O(1) since the matrix is always 2x2
  • Space: O(1)