Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Created May 29, 2021 23:18
Show Gist options
  • Save AmosAidoo/b6ae0f8039ab0b7b5691b60bd1215111 to your computer and use it in GitHub Desktop.
Save AmosAidoo/b6ae0f8039ab0b7b5691b60bd1215111 to your computer and use it in GitHub Desktop.
import numpy as np
import sys
from numpy import linalg as LA
"""
This function takes square matrix and returns
the dominant eigin value and the smallest eigen value
and the value closest to a scalar k
"""
def solve(sq_matrix, k):
if sq_matrix.shape[0] != sq_matrix.shape[1]:
return
vals, _ = LA.eig(sq_matrix)
k_close_idx = np.argmin(np.abs(vals - k))
return vals.max(), vals.min(), vals[k_close_idx]
if __name__ == '__main__':
n = int(input('Please input the size of the matrix: '))
elements = []
print("Please input the elements of the matrix row by row:")
print("Example:\n1 2 3 [Press enter]\n4 5 6 [Press enter]\n7 8 9 [Press enter]\n", "-" * 20)
for i in range(n):
line = input()
for element in line.split():
elements.append(float(element))
if len(elements) != n*n:
print(f"This is not a {n}x{n} matrix")
sys.exit(1)
k = float(input('Please input the value of k: '))
print("Solution:", solve(np.array(elements).reshape(n,n), k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment