Why avoid an explicit inverse when solving linear systems?
Environment
Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2, mpmath 1.3.0.
This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.
Overview
For a nonsingular matrix, the solution of $\mathbf{A}\mathbf{x}=\mathbf{b}$ can be written as $\mathbf{x}=\mathbf{A}^{-1}\mathbf{b}$. We compare the cost, error, and memory use of forming an inverse with solving the system directly.
Setup
Run the code in Jupyter Notebook from top to bottom.
Imports and plotting setup
import sys
from pathlib import Path
from pprint import pprint
from timeit import repeat
import matplotlib
import matplotlib.pyplot as plt
import mpmath as mp
import numpy as np
import scipy
from IPython.display import Math, display
from matplotlib.ticker import FuncFormatter
from matplotlib_inline.backend_inline import set_matplotlib_formats
from scipy.linalg import hilbert, lu_factor, lu_solve
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
%matplotlib inline
assert sys.version_info[:3] == (3, 14, 6)
assert sys.prefix != sys.base_prefix
print(f"Environment: wa-src({sys.version.split()[0]})")
print(f"NumPy {np.__version__}, SciPy {scipy.__version__}")
print(f"Matplotlib {matplotlib.__version__}, mpmath {mp.__version__}")
np.set_printoptions(formatter={"float_kind": lambda v: f"{v:.2e}"})
set_matplotlib_formats("svg")
plt.rcParams.update({"figure.figsize": (7, 4), "axes.grid": True,
"grid.alpha": 0.250, "svg.fonttype": "none"})
figure_dir = Path("104_nb_files")
figure_dir.mkdir(exist_ok=True)
rng = np.random.default_rng(104)
def save_figure(fig, name):
"""Format ticks, save as SVG, and display."""
fmt = FuncFormatter(lambda v, _: str(int(v)) if v == int(v) else f"{v:#.3g}")
for ax in fig.axes:
if ax.get_xscale() == "linear":
ax.xaxis.set_major_formatter(fmt)
if ax.get_yscale() == "linear" and ax.yaxis.units is None:
ax.yaxis.set_major_formatter(fmt)
fig.savefig(figure_dir / name, format="svg", bbox_inches="tight")
plt.show()
def seconds(func):
"""After warm-up, return the median time per run from five groups of three runs."""
func()
return float(np.median(repeat(func, number=3, repeat=5))) / 3
Environment: wa-src(3.14.6)
NumPy 2.5.4, SciPy 1.18.1
Matplotlib 3.11.2, mpmath 1.3.0
1. A solution formula is not a computational procedure
$$ \mathbf{A}=\begin{bmatrix}2&1\\1&1\end{bmatrix},\quad \mathbf{b}=\begin{bmatrix}3\\2\end{bmatrix},\quad \mathbf{A}\mathbf{x}=\mathbf{b}. $$
The determinant is $2\times1-1\times1=1$, so
$$ \mathbf{A}^{-1}=\frac{1}{2\times1-1\times1} \begin{bmatrix}1&-1\\-1&2\end{bmatrix},\qquad \mathbf{x}=\begin{bmatrix}1\times3-1\times2\\-1\times3+2\times2\end{bmatrix} =\begin{bmatrix}1\\1\end{bmatrix}. $$
Factor the matrix into lower and upper triangular matrices:
$$ \mathbf{A}=\mathbf{L}\mathbf{U} =\begin{bmatrix}1&0\\1/2&1\end{bmatrix} \begin{bmatrix}2&1\\0&1/2\end{bmatrix}. $$
Solve $\mathbf{L}\mathbf{y}=\mathbf{b}$ from top to bottom, then $\mathbf{U}\mathbf{x}=\mathbf{y}$ from bottom to top.
$$ \begin{aligned} y_1&=3,& y_2&=2-\frac12y_1=2-\frac32=\frac12,\\ x_2&=\frac{y_2}{1/2}=1,& x_1&=\frac{y_1-x_2}{2}=\frac{3-1}{2}=1. \end{aligned} $$
In general, a row permutation $\mathbf{P}$ gives $\mathbf{P}\mathbf{A}=\mathbf{L}\mathbf{U}$, and we solve $\mathbf{L}\mathbf{y}=\mathbf{P}\mathbf{b}$. NumPy’s solve uses LAPACK’s gesv routine.
A = np.array([[2, 1], [1, 1]], dtype=float)
b = np.array([3, 2], dtype=float)
pprint({"solve": np.linalg.solve(A, b), "inv @ b": np.linalg.inv(A) @ b})
display(Math(r"\mathbf{x}=\begin{bmatrix}1\\1\end{bmatrix}"))
{'inv @ b': array([1.00e+00, 1.00e+00]), 'solve': array([1.00e+00, 1.00e+00])}
$$ \displaystyle \mathbf{x}=\begin{bmatrix}1\\1\end{bmatrix} $$
2. An inverse performs extra work
LU factorization of a dense $n$-by-$n$ matrix multiplies and subtracts entries in the remaining submatrix. Ignoring lower-order terms such as divisions, the operation count is
$$ F(n)\simeq2\sum_{m=1}^{n-1}m^2 =\frac{(n-1)n(2n-1)}{3} \simeq\frac23n^3. $$
One triangular solve requires about $2\sum_{i=1}^{n}(i-1)=n(n-1)$ operations, so two require about $2n^2$.
If $\mathbf{c}_j$ is column $j$ of the inverse, then $\mathbf{A}\mathbf{c}_j=\mathbf{e}_j$, where $\mathbf{e}_j$ has a one only in position $j$. Computing all columns by triangular solves gives the following estimate.
$$ \begin{aligned} \text{Direct solve}&:\quad F(n)+2n^2,\\ \text{Via the inverse}&:\quad F(n)+n\times2n^2+2n^2. \end{aligned} $$
The last term is the inverse multiplied by the right-hand side. Specialized algorithms change the constants, so this is not an exact operation count for inv. Both approaches cost $O(n^3)$, but forming an inverse adds work.
Measure execution time using matrices with enlarged diagonal entries. Exclude matrix generation, but include factorization or inversion. BLAS uses its default settings, and the timing ratio depends on the environment.
sizes = [64, 128, 256, 512, 1024]
times = {"solve": [], "inv @ b": []}
for n in sizes:
A = rng.standard_normal((n, n)) + n * np.eye(n)
b = rng.standard_normal(n)
times["solve"].append(seconds(lambda: np.linalg.solve(A, b)))
times["inv @ b"].append(seconds(lambda: np.linalg.inv(A) @ b))
fig, ax = plt.subplots(layout="constrained")
for name, values in times.items():
ax.loglog(sizes, values, "o-", label=name)
ax.set(xlabel="Matrix size n", ylabel="Time [s]", title="One right-hand side")
ax.legend()
save_figure(fig, "01_solve_time.svg")
3. Separate rounding error from conditioning
Let $\mathbf{E}$ be the error in the computed inverse and $\mathbf{d}$ the error in the matrix–vector product. Then
$$ \begin{aligned} \widehat{\mathbf{x}}&=(\mathbf{A}^{-1}+\mathbf{E})\mathbf{b}+\mathbf{d},\\ \widehat{\mathbf{x}}-\mathbf{x}&=\mathbf{E}\mathbf{b}+\mathbf{d},\\ \mathbf{r}=\mathbf{b}-\mathbf{A}\widehat{\mathbf{x}} &=-\mathbf{A}\mathbf{E}\mathbf{b}-\mathbf{A}\mathbf{d}. \end{aligned} $$
Errors from both inversion and multiplication enter the residual. Cancellation of large terms can produce a large relative error. However, using an inverse does not always reduce accuracy. Under certain assumptions, its forward error can be comparable to that of a direct solve; see the paper by Druinsky and Toledo.
The residual alone also does not establish accuracy. Assume $\mathbf{b}\ne\mathbf{0}$ and use 2-norms. Since $\mathbf{A}(\mathbf{x}-\widehat{\mathbf{x}})=\mathbf{r}$,
$$ \begin{aligned} \|\mathbf{x}-\widehat{\mathbf{x}}\|_2 &=\|\mathbf{A}^{-1}\mathbf{r}\|_2 \le\|\mathbf{A}^{-1}\|_2\|\mathbf{r}\|_2,\\ \|\mathbf{b}\|_2&=\|\mathbf{A}\mathbf{x}\|_2 \le\|\mathbf{A}\|_2\|\mathbf{x}\|_2,\\ \frac{\|\mathbf{x}-\widehat{\mathbf{x}}\|_2}{\|\mathbf{x}\|_2} &\le\|\mathbf{A}^{-1}\|_2\|\mathbf{A}\|_2 \frac{\|\mathbf{r}\|_2}{\|\mathbf{b}\|_2} =\kappa_2(\mathbf{A})\rho. \end{aligned} $$
$\rho=\|\mathbf{r}\|_2/\|\mathbf{b}\|_2$ is the relative residual. When $\kappa_2(\mathbf{A})$ is large, even solve can have a large forward error. The inequality is an upper bound.
Checking with Hilbert matrices
Use matrices with entries $h_{ij}=1/(i+j-1)$. Forming the right-hand side $\mathbf{H}\mathbf{1}$ in double precision can make the exact solution differ from $\mathbf{1}$ because of rounding. We therefore transfer the stored inputs to 80-digit precision to compute a reference solution and residual.
orders = np.arange(3, 13)
errors = {name: [] for name in ("solve", "inv @ b")}
residuals = {name: [] for name in errors}
conditions = []
with mp.workdps(80):
for n in orders:
H = hilbert(int(n))
b = H @ np.ones(n)
# Pass float values directly to avoid rounding to short decimal strings.
H_mp, b_mp = mp.matrix(H.tolist()), mp.matrix(b.tolist())
reference = mp.lu_solve(H_mp, b_mp)
conditions.append(np.linalg.cond(H))
for name, x in (("solve", np.linalg.solve(H, b)),
("inv @ b", np.linalg.inv(H) @ b)):
x_mp = mp.matrix(x.tolist())
errors[name].append(float(mp.norm(x_mp - reference) / mp.norm(reference)))
residuals[name].append(float(mp.norm(b_mp - H_mp * x_mp) / mp.norm(b_mp)))
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
for name in errors:
axes[0].semilogy(orders, errors[name], "o-", label=name)
axes[1].semilogy(orders, residuals[name], "o-", label=name)
for ax, title in zip(axes, ["Relative forward error", "Relative residual"]):
ax.set(xlabel="Hilbert matrix size n", ylabel="Relative value", title=title)
ax.set_xticks([3, 6, 9, 12])
ax.legend()
save_figure(fig, "02_error_and_residual.svg")
pprint({"condition number (n=12)": f"{conditions[-1]:.2e}"})
pprint({name: {"forward error": f"{errors[name][-1]:.2e}",
"relative residual": f"{residuals[name][-1]:.2e}"} for name in errors})
{'condition number (n=12)': '1.72e+16'}
{'inv @ b': {'forward error': '6.06e+00', 'relative residual': '4.87e-02'},
'solve': {'forward error': '1.06e-01', 'relative residual': '6.88e-17'}}
In this example, inv @ b produces a large residual. As matrix size increases, solve also fails to keep solution error small. Check the residual together with the condition number, bearing in mind that computing the condition number itself is not cheap.
4. Multiple right-hand sides and factor reuse
Solve $\mathbf{A}\mathbf{X}=\mathbf{B}$, where $\mathbf{B}$ contains the right-hand sides. For $k$ right-hand sides, reusing the LU factors costs about $F(n)+2kn^2$, compared with $k\{F(n)+2n^2\}$ if the factorization is repeated each time.
SciPy’s lu_solve reuses the result of lu_factor. If the matrix changes, compute new factors.
n, k = 256, 32
A = rng.standard_normal((n, n)) + n * np.eye(n)
B = rng.standard_normal((n, k))
factor = lu_factor(A)
X = lu_solve(factor, B)
pprint({"relative residual (Frobenius)": f"{np.linalg.norm(B - A @ X) / np.linalg.norm(B):.2e}"})
methods = {
"solve each column": lambda: np.column_stack([np.linalg.solve(A, b) for b in B.T]),
"inv @ B": lambda: np.linalg.inv(A) @ B,
"one LU + solves": lambda: lu_solve(lu_factor(A), B),
}
batch_times = {name: seconds(func) for name, func in methods.items()}
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.barh(list(batch_times), list(batch_times.values()))
ax.set(xlabel="Time [s]", title="32 right-hand sides, n = 256")
save_figure(fig, "03_multiple_rhs.svg")
{'relative residual (Frobenius)': '1.06e-15'}
5. A sparse matrix can have a dense inverse
A tridiagonal matrix with diagonal entries two and adjacent entries $-1$ has $n+2(n-1)=3n-2$ nonzeros, but every entry of its inverse is nonzero. Convert a small example to dense form and plot the nonzero locations.
n = 40
S = diags([-np.ones(n - 1), 2 * np.ones(n), -np.ones(n - 1)],
offsets=[-1, 0, 1], format="csc")
C = np.linalg.inv(S.toarray())
b = np.ones(n)
x = spsolve(S, b)
pprint({"relative residual": f"{np.linalg.norm(b - S @ x) / np.linalg.norm(b):.2e}"})
fig, axes = plt.subplots(1, 2, figsize=(8, 4), layout="constrained")
for ax, matrix, title in zip(axes, [S, C], ["Tridiagonal matrix", "Its inverse"]):
ax.spy(matrix, markersize=2)
ax.set(title=title, xlabel="Column", ylabel="Row")
ax.grid(False)
save_figure(fig, "04_nonzero_pattern.svg")
{'relative residual': '1.59e-14'}
A dense double-precision matrix requires $8n^2$ bytes. CSC storage contains the nonzero values, row indices, and column starting positions, which cost $O(n)$ for this example. The figure compares array storage only, excluding object overhead and workspace.
sizes = 2 ** np.arange(6, 14)
sparse_bytes = []
for n in sizes:
S = diags([-np.ones(n - 1), 2 * np.ones(n), -np.ones(n - 1)],
offsets=[-1, 0, 1], format="csc")
sparse_bytes.append(S.data.nbytes + S.indices.nbytes + S.indptr.nbytes)
# Compute storage from the entry count without forming an inverse.
dense_bytes = 8 * sizes ** 2
fig, ax = plt.subplots(layout="constrained")
ax.loglog(sizes, np.array(sparse_bytes) / 2 ** 20, "o-", label="CSC matrix")
ax.loglog(sizes, dense_bytes / 2 ** 20, "o-", label="Dense inverse")
ax.set(xlabel="Matrix size n", ylabel="Array storage [MiB]", title="Storage")
ax.legend()
save_figure(fig, "05_storage.svg")
Use a routine such as SciPy’s spsolve for sparse systems. Sparse LU factors can contain new nonzeros where the original matrix had zeros, so a solve does not always use only $O(n)$ memory.
Conclusion
We compared the cost, error, and memory use of solving through an explicit inverse, and showed how to reuse a factorization.
Use solve for a linear system, and reuse LU factors when the matrix stays fixed but the right-hand side changes. Ill-conditioning still affects accuracy. Some tasks need every inverse entry or symbolic inversion; when only the solution is needed, avoid forming the inverse.