feat(maths): add LU decomposition algorithm for matrix factorization#14697
feat(maths): add LU decomposition algorithm for matrix factorization#14697MD-Mushfiqur123 wants to merge 5 commits into
Conversation
This commit introduces a complete implementation of the LU decomposition algorithm in the maths module, providing a fundamental numerical linear algebra tool for matrix factorization and solving systems of linear equations efficiently. LU Decomposition Overview: LU decomposition factorizes a square matrix A into the product of two triangular matrices: a lower triangular matrix L and an upper triangular matrix U, such that A = L * U. This decomposition is named after the mathematician Tadeusz Banachiewicz who formalized it in 1938, though the underlying algorithm traces back to the work of Alan Turing in 1948. The Doolittle algorithm implementation used in this contribution produces an L matrix with ones on the main diagonal (unit lower triangular) and a general upper triangular U matrix. This is one of the most commonly used variants of LU decomposition and is particularly well-suited for solving systems of linear equations. Mathematical Foundation: Given a square matrix A of size n x n, the decomposition computes: A = L * U where: - L is a lower triangular matrix with L[i][i] = 1 for all i - U is an upper triangular matrix with U[i][j] = 0 for all i > j The algorithm computes elements of L and U iteratively: For each column k from 0 to n-1: 1. Compute the k-th row of U: U[k][j] = A[k][j] - sum(L[k][s] * U[s][j] for s < k) 2. Compute the k-th column of L: L[i][k] = (A[i][k] - sum(L[i][s] * U[s][k] for s < k)) / U[k][k] The algorithm requires that all pivot elements U[k][k] be non-zero. If a zero pivot is encountered, the matrix may be singular or may require partial pivoting (row exchanges) for numerical stability. Implementation Details: The module provides two main functions: 1. lu_decomposition(matrix): Takes a square matrix as input and returns the (L, U) tuple. Includes comprehensive input validation: - Checks that the matrix is square - Detects zero pivots and raises informative errors - Converts all input values to floats for consistent arithmetic 2. solve_with_lu(lower, upper, b): Solves the system Ax = b given the LU decomposition of A. Uses a two-step approach: - Forward substitution to solve L * y = b - Back substitution to solve U * x = y Both functions include detailed docstrings following PEP 257 conventions, with comprehensive doctests that verify correctness across multiple test cases including: - Standard 2x2 and 3x3 matrices - Identity matrix (trivial case) - Singular matrix detection (zero pivot) - Non-square matrix validation - System of equations solving Algorithmic Complexity: Time Complexity: O(n^3) for the decomposition, O(n^2) for solving a system given the decomposition. This is the same asymptotic complexity as Gaussian elimination, but LU decomposition has the advantage that once the factorization is computed, solving multiple systems with the same coefficient matrix only requires O(n^2) work per system instead of O(n^3). Space Complexity: O(n^2) for storing the L and U matrices. Practical Applications: LU decomposition is used extensively in: - Engineering simulations (finite element analysis, CFD) - Computer graphics (transformation matrices) - Machine learning (linear regression, covariance computation) - Economics (input-output models, Leontief models) - Circuit analysis (nodal and mesh analysis) - Structural engineering (stiffness matrix solutions) This implementation provides an educational reference for understanding the algorithm while being functional enough for small to medium-sized matrices in practical applications.
There was a problem hiding this comment.
Click here to look at the relevant links ⬇️
🔗 Relevant Links
Repository:
Python:
Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.
algorithms-keeper commands and options
algorithms-keeper actions can be triggered by commenting on this PR:
@algorithms-keeper reviewto trigger the checks for only added pull request files@algorithms-keeper review-allto trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.
|
|
||
|
|
||
| def solve_with_lu( | ||
| lower: list[list[float]], upper: list[list[float]], b: list[float] |
There was a problem hiding this comment.
Please provide descriptive name for the parameter: b
for more information, see https://pre-commit.ci
There was a problem hiding this comment.
Click here to look at the relevant links ⬇️
🔗 Relevant Links
Repository:
Python:
Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.
algorithms-keeper commands and options
algorithms-keeper actions can be triggered by commenting on this PR:
@algorithms-keeper reviewto trigger the checks for only added pull request files@algorithms-keeper review-allto trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.
| """ | ||
|
|
||
|
|
||
| Matrix = list[list[float]] |
There was a problem hiding this comment.
Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: Matrix
|
|
||
|
|
||
| def solve_with_lu( | ||
| lower: list[list[float]], upper: list[list[float]], b: list[float] |
There was a problem hiding this comment.
Please provide descriptive name for the parameter: b
for more information, see https://pre-commit.ci
There was a problem hiding this comment.
Click here to look at the relevant links ⬇️
🔗 Relevant Links
Repository:
Python:
Automated review generated by algorithms-keeper. If there's any problem regarding this review, please open an issue about it.
algorithms-keeper commands and options
algorithms-keeper actions can be triggered by commenting on this PR:
@algorithms-keeper reviewto trigger the checks for only added pull request files@algorithms-keeper review-allto trigger the checks for all the pull request files, including the modified files. As we cannot post review comments on lines not part of the diff, this command will post all the messages in one comment.NOTE: Commands are in beta and so this feature is restricted only to a member or owner of the organization.
| Reference: https://en.wikipedia.org/wiki/LU_decomposition | ||
| """ | ||
|
|
||
| Matrix = list[list[float]] |
There was a problem hiding this comment.
Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: Matrix
|
|
||
|
|
||
| def solve_with_lu( | ||
| lower: list[list[float]], upper: list[list[float]], b: list[float] |
There was a problem hiding this comment.
Please provide descriptive name for the parameter: b
|
yes
সোম, ১৮ মে, ২০২৬ তারিখে ৯:৪৩ PM টায় তারিখে algorithms-keeper[bot] <
***@***.***> লিখেছেন:
… ***@***.***[bot]* commented on this pull request.
*Click here to look at the relevant links ⬇️*
🔗 Relevant Links Repository:
- Contributing guidelines
<https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md>
- Project Euler solution guidelines
<https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md>
Python:
- Formatted string literals (f-strings)
<https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings>
- Type hints <https://docs.python.org/3/library/typing.html>
- doctest <https://docs.python.org/3/library/doctest.html>
- unittest <https://docs.python.org/3/library/unittest.html>
- pytest <https://docs.pytest.org/en/stable/>
Automated review generated by algorithms-keeper
<https://github.com/dhruvmanila/algorithms-keeper>. If there's any
problem regarding this review, please open an issue about it.
<https://github.com/dhruvmanila/algorithms-keeper/issues>
------------------------------
algorithms-keeper commands and options
algorithms-keeper actions can be triggered by commenting on this PR:
- @algorithms-keeper review to trigger the checks for only added pull
request files
- @algorithms-keeper review-all to trigger the checks for all the pull
request files, including the modified files. As we cannot post review
comments on lines not part of the diff, this command will post all the
messages in one comment.
NOTE: Commands are in beta and so this feature is restricted only to a
member or owner of the organization.
------------------------------
In maths/lu_decomposition.py
<#14697?email_source=notifications&email_token=BRHACTQP4FFCTG7ERWEMQQL43MVS3A5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTIMZRGE3DGNBRGEZ2M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2K64DSL5ZGK5TJMV3V6Y3MNFRWW#discussion_r3260196406>
:
> + # Check for zero pivot
+ if upper[k][k] == 0:
+ raise ValueError(
+ "Zero pivot encountered. Matrix may be singular or require partial pivoting."
+ )
+
+ # Compute the k-th column of L
+ for i in range(k + 1, n):
+ sum_val = sum(lower[i][s] * upper[s][k] for s in range(k))
+ lower[i][k] = (matrix[i][k] - sum_val) / upper[k][k]
+
+ return lower, upper
+
+
+def solve_with_lu(
+ lower: list[list[float]], upper: list[list[float]], b: list[float]
Please provide descriptive name for the parameter: b
—
Reply to this email directly, view it on GitHub
<#14697?email_source=notifications&email_token=BRHACTRYTCTR23DG4TF7QE343MVS3A5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTIMZRGE3DGNBRGEZ2M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2L24DSL5ZGK5TJMV3V63TPORUWM2LDMF2GS33OONPWG3DJMNVQ#pullrequestreview-4311634113>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BRHACTUUSCJWCQZGCEWGK2343MVS3AVCNFSM6AAAAACZC3XABCVHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHM2DGMJRGYZTIMJRGM>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
|
hey
মঙ্গল, ১৯ মে, ২০২৬ তারিখে ৭:২৩ AM টায় তারিখে algorithms-keeper[bot] <
***@***.***> লিখেছেন:
… ***@***.***[bot]* commented on this pull request.
*Click here to look at the relevant links ⬇️*
🔗 Relevant Links Repository:
- Contributing guidelines
<https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md>
- Project Euler solution guidelines
<https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md>
Python:
- Formatted string literals (f-strings)
<https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings>
- Type hints <https://docs.python.org/3/library/typing.html>
- doctest <https://docs.python.org/3/library/doctest.html>
- unittest <https://docs.python.org/3/library/unittest.html>
- pytest <https://docs.pytest.org/en/stable/>
Automated review generated by algorithms-keeper
<https://github.com/dhruvmanila/algorithms-keeper>. If there's any
problem regarding this review, please open an issue about it.
<https://github.com/dhruvmanila/algorithms-keeper/issues>
------------------------------
algorithms-keeper commands and options
algorithms-keeper actions can be triggered by commenting on this PR:
- @algorithms-keeper review to trigger the checks for only added pull
request files
- @algorithms-keeper review-all to trigger the checks for all the pull
request files, including the modified files. As we cannot post review
comments on lines not part of the diff, this command will post all the
messages in one comment.
NOTE: Commands are in beta and so this feature is restricted only to a
member or owner of the organization.
------------------------------
In maths/lu_decomposition.py
<#14697?email_source=notifications&email_token=BRHACTXPBRWBD2TS3LSUYOT43OZPPA5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTIMZRGUYDKNRXGUYKM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2K64DSL5ZGK5TJMV3V6Y3MNFRWW#discussion_r3263116960>
:
> +"""
+LU Decomposition
+
+Decomposes a square matrix into a lower triangular matrix (L) and an
+upper triangular matrix (U) such that A = L * U.
+
+This decomposition is useful for:
+- Solving systems of linear equations efficiently
+- Computing matrix determinants
+- Finding matrix inverses
+- Repeated solving with the same coefficient matrix
+
+Reference: https://en.wikipedia.org/wiki/LU_decomposition
+"""
+
+Matrix = list[list[float]]
Variable and function names should follow the snake_case
<https://en.wikipedia.org/wiki/Snake_case> naming convention. Please
update the following name accordingly: Matrix
------------------------------
In maths/lu_decomposition.py
<#14697?email_source=notifications&email_token=BRHACTXPBRWBD2TS3LSUYOT43OZPPA5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTIMZRGUYDKNRXGUYKM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2K64DSL5ZGK5TJMV3V6Y3MNFRWW#discussion_r3263116964>
:
> + # Check for zero pivot
+ if upper[k][k] == 0:
+ raise ValueError(
+ "Zero pivot encountered. Matrix may be singular or require pivoting."
+ )
+
+ # Compute the k-th column of L
+ for i in range(k + 1, n):
+ sum_val = sum(lower[i][s] * upper[s][k] for s in range(k))
+ lower[i][k] = (a[i][k] - sum_val) / upper[k][k]
+
+ return lower, upper
+
+
+def solve_with_lu(
+ lower: list[list[float]], upper: list[list[float]], b: list[float]
Please provide descriptive name for the parameter: b
—
Reply to this email directly, view it on GitHub
<#14697?email_source=notifications&email_token=BRHACTRKN5NFNK7EMGL45OL43OZPPA5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTIMZRGUYDKNRXGUYKM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2L24DSL5ZGK5TJMV3V63TPORUWM2LDMF2GS33OONPWG3DJMNVQ#pullrequestreview-4315056750>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BRHACTXS525O7NEDFDM5VNL43OZPPAVCNFSM6AAAAACZC3XABCVHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHM2DGMJVGA2TMNZVGA>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
Describe your change:
Checklist:
LU Decomposition Algorithm
Adds LU decomposition (Doolittle algorithm) to the maths module for matrix factorization and solving systems of linear equations.
What This Adds
A new
maths/lu_decomposition.pyfile containing:lu_decomposition(matrix)Performs LU decomposition on a square matrix, returning
(L, U)where:solve_with_lu(lower, upper, b)Solves the system Ax = b using the LU decomposition, via:
Features
__main__blockAlgorithm
Uses the Doolittle algorithm with O(n^3) time complexity for decomposition and O(n^2) for solving. More efficient than Gaussian elimination when solving multiple systems with the same coefficient matrix.
Testing
All 10 doctests pass.