Solving Linear Systems with Direct Methods#
Teng-Jui Lin
Content adapted from UW AMATH 301, Beginning Scientific Computing, in Spring 2020.
Solving linear systems with direct methods
Matrix inversion by
scipy.linalg.inv()
LU decomposition with partial pivoting by
scipy.linalg.lu()
scipy
implementationsSolving linear systems by
scipy.linalg.solve()
Matrix inversion#
Given a system
However, we do not use matrix inversion because it is slow, have large error, and not all matrices have an inverse. Singular (non-invertable) matrices have
Problem Statement. Use matrix inversion to solve the linear system
import numpy as np
import scipy
from scipy import linalg
A = np.array([[1, 0, 0], [1, -1, 0], [2, -1, 3]])
b = np.array([5, -2, 9])
# solve by inversion
x = scipy.linalg.inv(A) @ b
x
array([5., 7., 2.])
LU decomposition#
Goal: Solve a system of form
We can decompose the matrix
so we have
where
LU decomposition is advantageous when the same
Problem Statement. Use LU decomposition to solve the linear system
A = np.array([[1, 0, 0], [1, -1, 0], [2, -1, 3]])
b = np.array([5, -2, 9])
# solve by LU decomposition
L, U = scipy.linalg.lu(A, permute_l=True)
y = scipy.linalg.solve(L, b)
x = scipy.linalg.solve(U, y)
x
array([5., 7., 2.])
LU decomposition with partial pivoting#
Partial pivoting uses permutation matrix
where
Problem Statement. Use LU decomposition with partial pivoting to solve the linear system
A = np.array([[1, 0, 0], [1, -1, 0], [2, -1, 3]])
b = np.array([5, -2, 9])
# solve by LU decomposition with partial pivoting
P, L, U = scipy.linalg.lu(A)
y = scipy.linalg.solve(L, P@b)
x = scipy.linalg.solve(U, y)
x
array([5., 7., 2.])
Solving linear systems with scipy
#
scipy.linalg.solve()
directly solves the linear system
Problem Statement. Use scipy.linalg.solve()
to solve the linear system
A = np.array([[1, 0, 0], [1, -1, 0], [2, -1, 3]])
b = np.array([5, -2, 9])
# solve by scipy
x = scipy.linalg.solve(A, b)
x
array([5., 7., 2.])