'Getting the real parts of eigenvalues in Python

I am trying to get the real parts of the eigenvalues, I coming across this error AttributeError: 'tuple' object has no attribute 'real'

def get_eig_real(matrix):
  eig= linalg.eig(M)
  eig=eig.real
  print(eig)
get_eig_real(M)


Solution 1:[1]

As @aaossa says, linalg.eig (see the docs) returns a tuple of two values, one containing the eigenvalues, the other the normalised eigenvectors

import numpy as np
from numpy import linalg

def get_eig_real(matrix):
    eigenvalues, eigenvectors = linalg.eig(matrix)
    return eigenvalues.real

test_matrix = np.diag((1, 2, 3))

real_eigenvalues = get_eig_real(test_matrix)
print(real_eigenvalues)

Solution 2:[2]

According to docs the function linalg.eig returns tuple of

The eigenvalues, each repeated according to its multiplicity.

And

The normalized (unit “length”) eigenvectors ...

Depending on your needs you can use either of those functions:

# to retrieve real parts of eigenvalues
def get_eig_real(matrix):
    eig, _ = linalg.eig(matrix)
    return eig.real

# to retrive real part of normilized eigenvectors
def get_eig_norm_real(matrix):
    _, norm_eigvectors = linalg.eig(matrix)
    return norm_eigvectors.real
   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew McClement
Solution 2 Vladyslav Chaikovskyi