11"""
2- In linear algebra, a QR decomposition, also known as a QR factorization
2+ In linear algebra, a QR decomposition, also known as a QR factorization
33or Q factorization,
44is a decomposition of a matrix a into a product a = QR
55of an orthonormal matrix Q and an upper triangular matrix R.
1515import numpy as np
1616from scipy .linalg import qr
1717
18+
1819def qr_decomposition (a : np .ndarray ) -> tuple [np .ndarray , np .ndarray ]:
1920 """
2021 Perform QR decomposition on a given matrix and raises an error if in
@@ -57,17 +58,12 @@ def qr_decomposition(a: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
5758 ValueError: row size should be greater than column size
5859 """
5960
60-
6161 rows , columns = np .shape (a )
6262 if rows < columns :
63- msg = (
64- "row size should be greater than column size"
65- )
63+ msg = "row size should be greater than column size"
6664 raise ValueError (msg )
6765 if rows < 2 or columns < 2 :
68- msg = (
69- "row size and column size should be greater than 2"
70- )
66+ msg = "row size and column size should be greater than 2"
7167 raise ValueError (msg )
7268 # Perform QR decomposition with pivoting
7369 # Q: Orthogonal matrix
@@ -79,14 +75,13 @@ def qr_decomposition(a: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
7975 # Note: The bottom row of R is all zeros because the matrix is rank-deficient.
8076 # Verification: a[:, P] should equal Q @ R
8177 ap = a [:, p ]
82- if ( np .allclose (ap , q @ r ) ):
83- return np .round (q ,2 ), np .round (r ,2 )
78+ if np .allclose (ap , q @ r ):
79+ return np .round (q , 2 ), np .round (r , 2 )
8480 else :
85- msg = (
86- "No matrix found which decompose given matrix"
87- )
81+ msg = "No matrix found which decompose given matrix"
8882 raise ValueError (msg )
8983
84+
9085if __name__ == "__main__" :
9186 import doctest
9287
0 commit comments