Created
May 29, 2021 23:18
-
-
Save AmosAidoo/b6ae0f8039ab0b7b5691b60bd1215111 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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