.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "api/gallery/linalg/lu/plot_02_lu_decomposition.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_api_gallery_linalg_lu_plot_02_lu_decomposition.py: LU decomposition with partial pivoting ========================================== Gaussian elimination, with its multipliers stored in ``L`` and the eliminated rows in ``U``, factors ``P A = L U``. The script reuses the factorization to solve multiple right-hand sides and compute the determinant, both far cheaper than refactoring from scratch each time. .. GENERATED FROM PYTHON SOURCE LINES 12-16 .. code-block:: Python import numpy as np from mathematicskit.linalg import lu_decompose, lu_det, lu_solve .. GENERATED FROM PYTHON SOURCE LINES 17-19 Factor once, solve for several right-hand sides ---------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 19-28 .. code-block:: Python A = np.array([[2.0, 1.0, 1.0], [4.0, 3.0, 3.0], [8.0, 7.0, 9.0]]) result = lu_decompose(A) print("P @ A == L @ U:", np.allclose(result.P @ A, result.L @ result.U)) for b in (np.array([5.0, 12.0, 24.0]), np.array([1.0, 0.0, -1.0])): x = lu_solve(result, b) print(f"b={b} -> x={np.round(x, 6)}, residual={np.linalg.norm(A @ x - b):.2e}") .. rst-class:: sphx-glr-script-out .. code-block:: none P @ A == L @ U: True b=[ 5. 12. 24.] -> x=[ 1.5 3. -1. ], residual=8.88e-16 b=[ 1. 0. -1.] -> x=[ 1.5 -2.5 0.5], residual=4.97e-16 .. GENERATED FROM PYTHON SOURCE LINES 29-31 Determinant via the pivoted triangular factors ---------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 31-35 .. code-block:: Python det_lu = lu_det(A) det_numpy = np.linalg.det(A) print(f"det via LU: {det_lu:.10f}, numpy.linalg.det: {det_numpy:.10f}") .. rst-class:: sphx-glr-script-out .. code-block:: none det via LU: 4.0000000000, numpy.linalg.det: 4.0000000000 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.001 seconds) .. _sphx_glr_download_api_gallery_linalg_lu_plot_02_lu_decomposition.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_02_lu_decomposition.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_02_lu_decomposition.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_02_lu_decomposition.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_