Skip to content

feat(maths): add LU decomposition algorithm for matrix factorization#14697

Open
MD-Mushfiqur123 wants to merge 2 commits into
TheAlgorithms:masterfrom
MD-Mushfiqur123:add-lu-decomposition-v2
Open

feat(maths): add LU decomposition algorithm for matrix factorization#14697
MD-Mushfiqur123 wants to merge 2 commits into
TheAlgorithms:masterfrom
MD-Mushfiqur123:add-lu-decomposition-v2

Conversation

@MD-Mushfiqur123
Copy link
Copy Markdown

Describe your change:

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

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.py file containing:

lu_decomposition(matrix)

Performs LU decomposition on a square matrix, returning (L, U) where:

  • L is a lower triangular matrix with ones on the diagonal
  • U is an upper triangular matrix
  • A = L * U

solve_with_lu(lower, upper, b)

Solves the system Ax = b using the LU decomposition, via:

  1. Forward substitution (L * y = b)
  2. Back substitution (U * x = y)

Features

  • Comprehensive docstrings with mathematical explanation
  • Full doctest coverage (10 tests, all passing)
  • Input validation (square matrix check, zero pivot detection)
  • Type hints for all parameters and return values
  • Demonstration code in __main__ block

Algorithm

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

python -m doctest maths/lu_decomposition.py -v

All 10 doctests pass.

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.
@algorithms-keeper algorithms-keeper Bot added the require descriptive names This PR needs descriptive function and/or variable names label May 18, 2026
Copy link
Copy Markdown

@algorithms-keeper algorithms-keeper Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 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.

Comment thread maths/lu_decomposition.py


def solve_with_lu(
lower: list[list[float]], upper: list[list[float]], b: list[float]
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: b

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label May 18, 2026
@algorithms-keeper algorithms-keeper Bot added the tests are failing Do not merge until tests pass label May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed require descriptive names This PR needs descriptive function and/or variable names tests are failing Do not merge until tests pass

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant