1414"""
1515
1616
17+ Matrix = list [list [float ]]
18+
19+
1720def lu_decomposition (
18- matrix : list [ list [ float ]] ,
19- ) -> tuple [list [ list [ float ]], list [ list [ float ]] ]:
21+ matrix : Matrix ,
22+ ) -> tuple [Matrix , Matrix ]:
2023 """Perform LU decomposition on a square matrix.
2124
2225 Decomposes the input matrix A into L (lower triangular) and U (upper
@@ -44,8 +47,13 @@ def lu_decomposition(
4447 encountered (matrix is singular or requires pivoting).
4548
4649 Examples:
47- >>> lu_decomposition([[2, 1, 1], [4, 3, 3], [8, 7, 9]])
48- ([[1.0, 0.0, 0.0], [2.0, 1.0, 0.0], [4.0, 3.0, 1.0]], [[2.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 2.0]])
50+ >>> l, u = lu_decomposition(
51+ ... [[2, 1, 1], [4, 3, 3], [8, 7, 9]]
52+ ... ) # doctest: +NORMALIZE_WHITESPACE
53+ >>> l
54+ [[1.0, 0.0, 0.0], [2.0, 1.0, 0.0], [4.0, 3.0, 1.0]]
55+ >>> u
56+ [[2.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 2.0]]
4957
5058 >>> lu_decomposition([[1, 2], [3, 4]])
5159 ([[1.0, 0.0], [3.0, 1.0]], [[1.0, 2.0], [0.0, -2.0]])
@@ -56,10 +64,10 @@ def lu_decomposition(
5664 >>> lu_decomposition([[1, 0], [0, 1]])
5765 ([[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]])
5866
59- >>> lu_decomposition([[0, 1], [1, 0]])
67+ >>> lu_decomposition([[0, 1], [1, 0]]) # doctest: +ELLIPSIS
6068 Traceback (most recent call last):
6169 ...
62- ValueError: Zero pivot encountered. Matrix may be singular or require partial pivoting .
70+ ValueError: Zero pivot encountered.. .
6371
6472 >>> lu_decomposition([[1, 2, 3], [4, 5, 6]])
6573 Traceback (most recent call last):
@@ -92,13 +100,14 @@ def lu_decomposition(
92100 # Check for zero pivot
93101 if upper [k ][k ] == 0 :
94102 raise ValueError (
95- "Zero pivot encountered. Matrix may be singular or require partial pivoting."
103+ "Zero pivot encountered. "
104+ "Matrix may be singular or require pivoting."
96105 )
97106
98107 # Compute the k-th column of L
99108 for i in range (k + 1 , n ):
100109 sum_val = sum (lower [i ][s ] * upper [s ][k ] for s in range (k ))
101- lower [i ][k ] = (matrix [i ][k ] - sum_val ) / upper [k ][k ]
110+ lower [i ][k ] = (a [i ][k ] - sum_val ) / upper [k ][k ]
102111
103112 return lower , upper
104113
0 commit comments