How to compute eigenvalues with SciPy

A square matrix can stretch, shrink, or reverse certain nonzero directions without changing their line of action. The scale factors for those directions are eigenvalues, and SciPy can compute them with the corresponding eigenvectors for numerical models and stability checks.

The scipy.linalg.eig() function handles a general dense square matrix and returns right eigenvectors as columns by default. Eigenvector column i belongs to eigenvalue i, and real input can still produce arrays with a complex data type.

An upper-triangular sample makes the expected eigenvalues visible on the diagonal, while a residual calculation tests A @ v = w * v for every returned eigenpair. Use scipy.linalg.eigh() instead when the input is real symmetric or complex Hermitian because it is specialized for that matrix structure.

Steps to compute eigenvalues with SciPy:

  1. Create compute_eigenvalues.py with the imports and square matrix.
    compute_eigenvalues.py
    import numpy as np
    from scipy.linalg import eig
     
     
    matrix = np.array(
        [
            [4.0, 1.0, -2.0],
            [0.0, 3.0, 1.0],
            [0.0, 0.0, 2.0],
        ]
    )
    np.set_printoptions(precision=6, suppress=True)
  2. Append the general eigenvalue calculation below the matrix definition.
    eigenvalues, eigenvectors = eig(matrix)

    eig() may return complex-valued eigenvalues even for a real matrix. The matching right eigenvectors are stored by column in eigenvectors.

  3. Append the eigenpair residual calculation below the eigensolver call.
    residuals = np.linalg.norm(
        matrix @ eigenvectors - eigenvectors * eigenvalues,
        axis=0,
    )
    verified = np.all(residuals < 1e-10)

    Multiplying eigenvectors * eigenvalues scales each eigenvector column by its matching eigenvalue. Each residual should approach zero when A @ v = w * v holds.

  4. Append the result display below the residual calculation.
    print("eigenvalues:", eigenvalues)
    print("residuals:", residuals)
    print("max_residual:", residuals.max())
    print("verified:", verified)
  5. Run the completed eigenvalue script to verify every eigenpair residual.
    $ python compute_eigenvalues.py
    eigenvalues: [4.+0.j 3.+0.j 2.+0.j]
    residuals: [0. 0. 0.]
    max_residual: 2.220446049250313e-16
    verified: True

    The three eigenvalues match the diagonal entries, and verified: True confirms that every computed eigenpair has a residual below 1e-10.