Back to Problems
## Calculate Eigenvalues of a Matrix (medium)

#### Example

## Calculate Eigenvalues

Eigenvalues of a matrix offer significant insight into the matrix's behavior, particularly in the context of linear transformations and systems of linear equations.
### Definition

For a square matrix \(A\), eigenvalues are scalars \(\lambda\) that satisfy the equation for some non-zero vector \(v\) (eigenvector):
\[
Av = \lambda v
\]
### Calculation for a 2x2 Matrix

The eigenvalues of a 2x2 matrix \(A\), given by:
\[
A = \begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
\]
are determined by solving the characteristic equation:
\[
\det(A - \lambda I) = 0
\]
This simplifies to a quadratic equation:
\[
\lambda^2 - \text{tr}(A) \lambda + \det(A) = 0
\]
Here, the trace of A, denoted as tr(A), is \(a + d\), and the determinant of A, denoted as det(A), is \(ad - bc\). Solving this equation yields the eigenvalues, \(\lambda\).
### Significance

Understanding eigenvalues is essential for analyzing the effects of linear transformations represented by the matrix. They are crucial in various applications, including stability analysis, vibration analysis, and Principal Component Analysis (PCA) in machine learning.

Write a Python function that calculates the eigenvalues of a 2x2 matrix. The function should return a list containing the eigenvalues, sort values from highest to lowest.

Example: input: matrix = [[2, 1], [1, 2]] output: [3.0, 1.0] reasoning: The eigenvalues of the matrix are calculated using the characteristic equation of the matrix, which for a 2x2 matrix is $\lambda^2 - ext{trace}(A)\lambda + ext{det}(A) = 0$, where $\lambda$ are the eigenvalues.

def calculate_eigenvalues(matrix: list[list[float]]) -> list[float]: a, b, c, d = matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1] trace = a + d determinant = a * d - b * c # Calculate the discriminant of the quadratic equation discriminant = trace**2 - 4 * determinant # Solve for eigenvalues lambda_1 = (trace + discriminant**0.5) / 2 lambda_2 = (trace - discriminant**0.5) / 2 return [lambda_1, lambda_2]

Output will be shown here.

Solution copied to clipboard!