Understanding forward error, backward error, and numerical stability

Environment

Python 3.14.6, NumPy 2.5.4, Matplotlib 3.11.2.

This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.

Overview

Forward error measures the difference in the solution; backward error measures the input change needed to make the computed result exact. We define both and relate them to residuals and condition numbers for linear systems. Python examples of cancellation and pivoting distinguish properties of the problem from properties of the algorithm.

Setup

Run the code in Jupyter Notebook from top to bottom.

Imports and plotting setup
import sys
from decimal import Decimal, localcontext
from pathlib import Path
from pprint import pprint

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Math, display
from matplotlib.ticker import FuncFormatter, NullFormatter
from matplotlib_inline.backend_inline import set_matplotlib_formats

%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__}, Matplotlib: {matplotlib.__version__}")
# Save SVG and include PNG output for display in untrusted notebooks.
set_matplotlib_formats("svg", "png")
np.set_printoptions(formatter={"float_kind": lambda v: f"{v:.2e}"})
plt.rcParams.update({"figure.figsize": (7, 4), "font.size": 11,
                     "axes.grid": True, "grid.alpha": 0.250,
                     "svg.fonttype": "none"})
figure_dir = Path("103_nb_files")
figure_dir.mkdir(exist_ok=True)


def latex_number(value):
    """Format a computed value as a formula with three significant digits."""
    mantissa, exponent = f"{float(value):.2e}".split("e")
    return rf"{mantissa}\times10^{{{int(exponent)}}}"


def save_figure(fig, filename):
    """Format decimal ticks, save the SVG, and display it."""
    for ax in fig.axes:
        for axis in (ax.xaxis, ax.yaxis):
            if axis.get_scale() == "linear":
                axis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:#.3g}"))
            axis.set_minor_formatter(NullFormatter())
    fig.savefig(figure_dir / filename, format="svg", bbox_inches="tight")
    plt.show()
    plt.close(fig)
Environment: wa-src(3.14.6)
NumPy: 2.5.4, Matplotlib: 3.11.2

1. Forward and backward errors

Let $a$ be the input, $y=f(a)$ the exact output, and $\widehat y$ the computed result. For $a\ne0$ and $y\ne0$, relative forward and backward errors are defined as follows.

$$ E_f=\frac{|\widehat y-f(a)|}{|f(a)|},\qquad \eta=\min_{f(a+\Delta a)=\widehat y}\frac{|\Delta a|}{|a|}. $$

Absolute errors omit the denominators. If an input or output is zero, use absolute error or another suitable measure instead of relative error. Backward error requires specifying which input changes are allowed and how they are measured. A corresponding input may not exist. See Higham’s explanation.

Take $f(a)=a^2$, $a=1$, and set $\widehat y=1.21$ for illustration. This is not a measured rounding error.

$$ \begin{aligned} E_f&=\frac{|1.21-1|}{1}=0.210,\\ (1+\Delta a)^2&=1.21,\\ 1+\Delta a&=\pm1.10,\\ \Delta a&=0.100\ \text{or}\ -2.10,\\ \eta&=\min(0.100,2.10)=0.100. \end{aligned} $$

The vertical distance in the figure is the absolute forward error, and the horizontal distance is the smallest input change. Since both denominators are one here, the absolute and relative errors have the same numerical values.

a = 1
y_hat = 1.21
forward = abs(y_hat - a**2) / a**2
backward = abs(np.sqrt(y_hat) - a) / abs(a)
display(Math(rf"E_f={latex_number(forward)},\quad\eta={latex_number(backward)}"))

t = np.linspace(0.900, 1.20, 200)
fig, ax = plt.subplots(layout="constrained")
ax.plot(t, t**2, label=r"$f(a)=a^2$")
ax.scatter([1, 1, 1.10], [1, 1.21, 1.21], color="black")
ax.annotate("", xy=(1, 1.21), xytext=(1, 1),
            arrowprops={"arrowstyle": "<->", "color": "tab:red"})
ax.annotate("", xy=(1.10, 1.21), xytext=(1, 1.21),
            arrowprops={"arrowstyle": "<->", "color": "tab:green"})
ax.text(0.905, 1.10, "Forward", color="tab:red")
ax.text(1.02, 1.24, "Backward", color="tab:green")
ax.set(xlabel="Input", ylabel="Output", title="Two ways to measure error")
ax.legend()
save_figure(fig, "01_error_directions.svg")

$$ \displaystyle E_f=2.10\times10^{-1},\quad\eta=1.00\times10^{-1} $$

2. Bounding forward error using the residual

Consider $\mathbf{A}\mathbf{x}=\mathbf{b}$ with a real, nonsingular square matrix and $\mathbf{b}\ne\mathbf{0}$. All norms below are 2-norms.

$$ \|\mathbf{v}\|_2=\sqrt{\sum_i v_i^2},\qquad \|\mathbf{A}\|_2=\max_{\mathbf{v}\ne\mathbf{0}} \frac{\|\mathbf{A}\mathbf{v}\|_2}{\|\mathbf{v}\|_2}. $$

Define the residual of an approximate solution $\widehat{\mathbf{x}}$ as $\mathbf{r}=\mathbf{b}-\mathbf{A}\widehat{\mathbf{x}}$. If the matrix stays fixed and only the right-hand side changes,

$$ \begin{aligned} \mathbf{A}\widehat{\mathbf{x}}&=\mathbf{b}+\Delta\mathbf{b},\\ \Delta\mathbf{b}&=\mathbf{A}\widehat{\mathbf{x}}-\mathbf{b}=-\mathbf{r},\\ \eta_b&=\frac{\|\Delta\mathbf{b}\|_2}{\|\mathbf{b}\|_2} =\frac{\|\mathbf{r}\|_2}{\|\mathbf{b}\|_2}. \end{aligned} $$

The relative residual is therefore the relative backward error with respect to the right-hand side alone. We next relate it to solution error.

$$ \begin{aligned} \mathbf{A}(\mathbf{x}-\widehat{\mathbf{x}})&=\mathbf{r},\\ \mathbf{x}-\widehat{\mathbf{x}}&=\mathbf{A}^{-1}\mathbf{r},\\ \|\mathbf{x}-\widehat{\mathbf{x}}\|_2&\le\|\mathbf{A}^{-1}\|_2\|\mathbf{r}\|_2,\\ \|\mathbf{b}\|_2&=\|\mathbf{A}\mathbf{x}\|_2\le\|\mathbf{A}\|_2\|\mathbf{x}\|_2,\\ E_f=\frac{\|\widehat{\mathbf{x}}-\mathbf{x}\|_2}{\|\mathbf{x}\|_2} &\le\|\mathbf{A}^{-1}\|_2\|\mathbf{A}\|_2 \frac{\|\mathbf{r}\|_2}{\|\mathbf{b}\|_2}. \end{aligned} $$

$$ \boxed{E_f\le\kappa_2(\mathbf{A})\eta_b},\qquad \kappa_2(\mathbf{A})=\|\mathbf{A}\|_2\|\mathbf{A}^{-1}\|_2. $$

With a large condition number, small backward error alone cannot guarantee small forward error. For example, for $0\lt \alpha\le1$, set

$$ \mathbf{A}=\begin{bmatrix}1&0\\0&\alpha\end{bmatrix},\quad \mathbf{b}=\begin{bmatrix}1\\0\end{bmatrix},\quad \mathbf{x}=\begin{bmatrix}1\\0\end{bmatrix},\quad \widehat{\mathbf{x}}=\begin{bmatrix}1\\1\end{bmatrix} $$

Then $\mathbf{r}=(0,-\alpha)^{\mathsf T}$, $\eta_b=\alpha$, $\kappa_2=1/\alpha$, and $E_f=1$. This approximate solution is deliberately constructed; it is not the output of solve.

alphas = np.logspace(-12, 0, 49)
b = np.array([1, 0], dtype=float)
x_true = b.copy()
x_hat = np.array([1, 1], dtype=float)
records = []
for alpha in alphas:
    A = np.diag([1, alpha])
    eta_b = np.linalg.norm(b - A @ x_hat) / np.linalg.norm(b)
    error = np.linalg.norm(x_hat - x_true) / np.linalg.norm(x_true)
    records.append([np.linalg.cond(A), eta_b, error])
records = np.array(records)
print("Columns: condition number, right-hand-side backward error, forward error")
pprint(records[[0, 24, -1]])
fig, ax = plt.subplots(layout="constrained")
ax.loglog(records[:, 0], records[:, 1], label=r"$\eta_b$")
ax.loglog(records[:, 0], records[:, 2], label=r"$E_f$")
ax.loglog(records[::4, 0], (records[:, 0] * records[:, 1])[::4],
          "o", label=r"$\kappa_2\eta_b$")
ax.set(xlabel="Condition number", ylabel="Relative error",
       title="Small residual does not guarantee an accurate solution")
ax.legend()
save_figure(fig, "02_residual_and_condition.svg")
Columns: condition number, right-hand-side backward error, forward error
array([[1.00e+12, 1.00e-12, 1.00e+00],
       [1.00e+06, 1.00e-06, 1.00e+00],
       [1.00e+00, 1.00e+00, 1.00e+00]])

Backward error when both the matrix and right-hand side may change

Another common definition allows changes to both $\mathbf{A}$ and $\mathbf{b}$.

$$ \eta_{A,b}=\min\{\epsilon\ge0: (\mathbf{A}+\Delta\mathbf{A})\widehat{\mathbf{x}}=\mathbf{b}+\Delta\mathbf{b},\quad \|\Delta\mathbf{A}\|_2\le\epsilon\|\mathbf{A}\|_2,\quad \|\Delta\mathbf{b}\|_2\le\epsilon\|\mathbf{b}\|_2\}. $$

Set $D=\|\mathbf{A}\|_2\|\widehat{\mathbf{x}}\|_2+\|\mathbf{b}\|_2$. Since $\mathbf{r}=\Delta\mathbf{A}\widehat{\mathbf{x}}-\Delta\mathbf{b}$, the triangle inequality gives $\|\mathbf{r}\|_2\le\epsilon D$. Thus $\epsilon\ge\|\mathbf{r}\|_2/D$ is necessary.

This lower bound can be attained. Assume $\mathbf{r}\ne\mathbf{0}$ and $\widehat{\mathbf{x}}\ne\mathbf{0}$. Set $\mathbf{v}=\mathbf{r}/\|\mathbf{r}\|_2$, $\mathbf{z}=\widehat{\mathbf{x}}/\|\widehat{\mathbf{x}}\|_2$, and $\epsilon=\|\mathbf{r}\|_2/D$. Then

$$ \begin{aligned} \Delta\mathbf{A}&=\epsilon\|\mathbf{A}\|_2\mathbf{v}\mathbf{z}^{\mathsf T},\quad \Delta\mathbf{b}=-\epsilon\|\mathbf{b}\|_2\mathbf{v},\\ \Delta\mathbf{A}\widehat{\mathbf{x}}-\Delta\mathbf{b} &=\epsilon(\|\mathbf{A}\|_2\|\widehat{\mathbf{x}}\|_2+\|\mathbf{b}\|_2)\mathbf{v} =\mathbf{r}. \end{aligned} $$

Both vectors are unit vectors, so $\|\mathbf{v}\mathbf{z}^{\mathsf T}\|_2=1$ and both norm constraints hold. Hence

$$ \boxed{\eta_{A,b}=\frac{\|\mathbf{r}\|_2} {\|\mathbf{A}\|_2\|\widehat{\mathbf{x}}\|_2+\|\mathbf{b}\|_2}}. $$

If the residual is zero, both perturbations can be zero. If the approximate solution is zero, changing the right-hand side to zero gives the same formula. This is a normwise measure, different from a bound on each component’s relative change. Its definition differs from $\eta_b$, so it cannot simply replace $\eta_b$ in the earlier bound.

3. Numerical stability and cancellation

Excluding effects such as overflow and underflow, a basic operation rounded to nearest can be modeled as $\operatorname{fl}(a\circ b)=(a\circ b)(1+\delta)$ with $|\delta|\le u$. The binary64 unit roundoff is $u=2^{-53}\approx1.11\times10^{-16}$. The value np.finfo(float).eps equals $2u$.

A method is backward stable if its backward error stays on the order of $C u$ for the inputs under consideration. The factor $C$ may depend on problem size and related quantities. Other notions, such as forward stability, also exist, but we focus on backward stability here. Conditioning describes problem sensitivity; stability describes an algorithm.

Comparing two forms of a subtraction

For $t\gt 0$, consider $f(t)=\sqrt{1+t}-1$. When $t$ is small, errors introduced before the subtraction become relatively large afterward. Rationalizing gives the following expression.

$$ \begin{aligned} f(t)&=\frac{(\sqrt{1+t}-1)(\sqrt{1+t}+1)}{\sqrt{1+t}+1}\\ &=\frac{(1+t)-1}{\sqrt{1+t}+1} =\frac{t}{\sqrt{1+t}+1}. \end{aligned} $$

Compute the relative condition number of the problem itself.

$$ \begin{aligned} f^{\prime}(t)&=\frac{1}{2\sqrt{1+t}},\\ \kappa_f(t)&=\left|\frac{tf^{\prime}(t)}{f(t)}\right| =\frac{t}{2\sqrt{1+t}(\sqrt{1+t}-1)}\\ &=\frac{\sqrt{1+t}+1}{2\sqrt{1+t}}\longrightarrow1\quad(t\to0^+). \end{aligned} $$

The input sensitivity is not large; the loss of accuracy comes from the computation. For reference values, convert the stored floating-point input exactly to Decimal and evaluate the rationalized expression at 80-digit precision. This is not the mathematical exact value, but is accurate enough to assess binary64 error.

ts = np.logspace(-18, -1, 120)
direct = np.sqrt(1 + ts) - 1
rationalized = ts / (np.sqrt(1 + ts) + 1)
errors = []
with localcontext() as ctx:
    ctx.prec = 80
    for t, y1, y2 in zip(ts, direct, rationalized):
        d = Decimal.from_float(float(t))
        reference = d / ((1 + d).sqrt() + 1)
        errors.append([float(abs(Decimal.from_float(float(y)) - reference) / reference)
                       for y in (y1, y2)])
errors = np.array(errors)
u = np.finfo(float).eps / 2
print("Columns: input, direct value, rationalized value, direct relative error, rationalized relative error")
pprint(np.column_stack([ts, direct, rationalized, errors])[[0, 60, -1]])
display(Math(rf"u={latex_number(u)}"))

# Dividing by t also reveals outputs rounded to zero on a linear vertical axis.
fig, ax = plt.subplots(layout="constrained")
ax.semilogx(ts, direct / ts, label="Direct")
ax.semilogx(ts, rationalized / ts, "--", label="Rationalized")
ax.set(xlabel=r"$t$", ylabel=r"Computed $f(t)/t$", title="Cancellation in subtraction")
ax.legend()
save_figure(fig, "03_cancellation_values.svg")

fig, ax = plt.subplots(layout="constrained")
ax.loglog(ts, errors[:, 0], label="Direct")
ax.loglog(ts, errors[:, 1], label="Rationalized")
ax.axhline(u, color="black", linestyle=":", label=r"$u$")
ax.set(xlabel=r"$t$", ylabel="Relative forward error", title="Error against an 80-digit reference")
ax.legend()
save_figure(fig, "04_cancellation_errors.svg")
Columns: input, direct value, rationalized value, direct relative error, rationalized relative error
array([[1.00e-18, 0.00e+00, 5.00e-19, 1.00e+00, 2.50e-19],
       [3.73e-10, 1.86e-10, 1.86e-10, 5.77e-07, 2.89e-17],
       [1.00e-01, 4.88e-02, 4.88e-02, 1.66e-15, 4.32e-17]])

$$ \displaystyle u=1.11\times10^{-16} $$

For small inputs, direct evaluation returns zero and the relative forward error is one. The rationalized calculation has error on the scale of $u$ over this range. Since the condition number is small and changing the formula reduces the error, the loss can be attributed to the computation. A finite set of experiments alone does not prove backward stability.

4. An example where pivoting changes the result

For $0\lt \tau\lt 1$, solve the following linear system.

$$ \mathbf{A}=\begin{bmatrix}\tau&1\\1&1\end{bmatrix},\qquad \mathbf{b}=\begin{bmatrix}1\\2\end{bmatrix}. $$

The second equation gives $x_2=2-x_1$. Substituting into the first gives $\tau x_1+2-x_1=1$, hence $(1-\tau)x_1=1$, so

$$ x_1=\frac{1}{1-\tau},\qquad x_2=2-\frac{1}{1-\tau}=\frac{1-2\tau}{1-\tau}. $$

Elimination without a row swap subtracts $m=1/\tau$ times the first row from the second.

$$ \begin{aligned} (1-m\tau)x_1+(1-m)x_2&=2-m,\\ (1-m)x_2&=2-m,\\ x_2&=\frac{2-m}{1-m},\\ x_1&=\frac{1-x_2}{\tau}. \end{aligned} $$

Small $\tau$ produces a large multiplier $m$, and the error in the final subtraction is also multiplied by $1/\tau$. With partial pivoting, swapping rows gives first pivot one and multiplier $\tau$. The comparison routine np.linalg.solve calls LAPACK’s GESV, which uses LU factorization with partial pivoting.

Evaluate the reference solution and residual at 80-digit Decimal precision. Computing the residual at the same binary64 precision as the solution can round it to zero and hide the error.

def assess(tau, A, b, x_hat):
    """Compute a high-precision reference solution and residual for the stored inputs."""
    with localcontext() as ctx:
        ctx.prec = 80
        d = Decimal.from_float(float(tau))
        z = [Decimal.from_float(float(v)) for v in x_hat]
        ref = [1 / (1 - d), (1 - 2 * d) / (1 - d)]
        forward = (sum((v - w)**2 for v, w in zip(z, ref))
                   / sum(w**2 for w in ref)).sqrt()
        residual = ((1 - d * z[0] - z[1])**2 + (2 - z[0] - z[1])**2).sqrt()
    scale = np.linalg.norm(A, 2) * np.linalg.norm(x_hat) + np.linalg.norm(b)
    return float(forward), float(residual) / scale


taus = np.logspace(-18, -2, 81)
no_pivot, pivot, conditions = [], [], []
for tau in taus:
    A = np.array([[tau, 1], [1, 1]])
    b = np.array([1, 2], dtype=float)
    # Implement two-dimensional elimination in the order of the formulas.
    multiplier = 1 / tau
    x2 = (2 - multiplier) / (1 - multiplier)
    naive = np.array([(1 - x2) / tau, x2])
    solved = np.linalg.solve(A, b)
    no_pivot.append(assess(tau, A, b, naive))
    pivot.append(assess(tau, A, b, solved))
    conditions.append(np.linalg.cond(A))
no_pivot, pivot = np.array(no_pivot), np.array(pivot)
print("Minimum and maximum condition numbers")
pprint(np.array([min(conditions), max(conditions)]))
print("Columns: tau, forward/backward errors without pivoting, forward/backward errors of solve")
pprint(np.column_stack([taus, no_pivot, pivot])[[0, 40, -1]])

for column, ylabel, filename in [
    (0, "Relative forward error", "05_pivot_forward.svg"),
    (1, "Relative backward error", "06_pivot_backward.svg"),
]:
    fig, ax = plt.subplots(layout="constrained")
    ax.loglog(taus, no_pivot[:, column], label="Without pivoting")
    ax.loglog(taus, pivot[:, column], label="NumPy solve")
    ax.axhline(u, color="black", linestyle=":", label=r"$u$")
    ax.set(xlabel=r"$\tau$", ylabel=ylabel, title="Effect of partial pivoting")
    ax.legend()
    save_figure(fig, filename)
Minimum and maximum condition numbers
array([2.62e+00, 2.65e+00])
Columns: tau, forward/backward errors without pivoting, forward/backward errors of solve
array([[1.00e-18, 7.07e-01, 2.59e-01, 1.00e-18, 2.21e-19],
       [1.00e-10, 5.84e-08, 1.83e-08, 8.26e-18, 1.83e-18],
       [1.00e-02, 3.25e-15, 1.01e-15, 1.16e-16, 2.64e-17]])

Condition numbers range from about $2.62$ to $2.65$, so the problem is not highly sensitive. Even so, elimination without row swaps produces large forward and backward errors. Partial pivoting works well for this example. In general, error also depends on element growth during elimination, so equal accuracy is not guaranteed for every matrix.

Conclusion

Forward error measures solution differences, while backward error measures input differences. Accuracy must be assessed using both conditioning and the stability of the calculation.

A small residual alone does not establish solution accuracy. Specify which data may change, compute the backward error, and compare it with the condition number. If error is large despite a small condition number, examine the calculation for effects such as cancellation or poor pivot choices.