66and is the basis for a particular eigenvalue algorithm, the QR algorithm.
77This algorithm will simply attempt to perform QR decomposition on any square matrix.
88Reference: https://en.wikipedia.org/wiki/QR_decomposition"""
9+
910from __future__ import annotations
1011from scipy .linalg import qr
1112import numpy as np
1213
14+
1315def qr_decomposition (matrix_a : np .ndarray ) -> tuple [np .ndarray , np .ndarray ]:
1416 """
1517 Perform QR decomposition on a given matrix and raises an error if in
@@ -52,17 +54,12 @@ def qr_decomposition(matrix_a: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
5254 ValueError: row size should be greater than column size
5355 """
5456
55-
5657 rows , columns = np .shape (matrix_a )
5758 if rows < columns :
58- msg = (
59- "row size should be greater than column size"
60- )
59+ msg = "row size should be greater than column size"
6160 raise ValueError (msg )
6261 if rows < 2 or columns < 2 :
63- msg = (
64- "row size and column size should be greater than 2"
65- )
62+ msg = "row size and column size should be greater than 2"
6663 raise ValueError (msg )
6764 # Perform QR decomposition with pivoting
6865 # matrix_q: Orthogonal matrix
@@ -73,15 +70,14 @@ def qr_decomposition(matrix_a: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
7370
7471 # Verification: matrix_a[:, pivot] should equal matrix_q @ matrix_r
7572 permute_matrix = matrix_a [:, pivot ]
76- if ( np .allclose (permute_matrix , matrix_q @ matrix_r ) ):
77- return np .round (matrix_q ,2 ), np .round (matrix_r ,2 )
73+ if np .allclose (permute_matrix , matrix_q @ matrix_r ):
74+ return np .round (matrix_q , 2 ), np .round (matrix_r , 2 )
7875 else :
79- msg = (
80- "No matrix found which decompose given matrix"
81- )
76+ msg = "No matrix found which decompose given matrix"
8277 raise ValueError (msg )
8378
79+
8480if __name__ == "__main__" :
8581 import doctest
8682
87- doctest .testmod ()
83+ doctest .testmod ()
0 commit comments