Skip to content
scipython.com

Kaczmarz's algorithm

Posted on

Kaczmarz's algorithm solves a system of linear equations by projecting an approximate solution onto the hyperplane of one equation after another. This post visualises its steps for systems of two unknowns, compares the orders in which the equations can be taken (cyclic, random and shuffled), and shows what becomes of the algorithm when the system has no solution.

Kaczmarz's algorithm solves a system of \(m\) linear equations in \(n\) unknowns, \(\boldsymbol{A}\boldsymbol{x} = \boldsymbol{b}\), by a sequence of projections. It was published in 1937 by the Polish mathematician Stefan Kaczmarz [S. Kaczmarz, Bulletin International de l'Académie Polonaise des Sciences et des Lettres A 35, 355 (1937); English translation in International Journal of Control 57, 1269 (1993), doi:10.1080/00207179308934446], and was rediscovered in 1970 as the algebraic reconstruction technique (ART), for the reconstruction of an image from its projections, the problem of computed tomography (CT) [R. Gordon, R. Bender and G. T. Herman, Journal of Theoretical Biology 29, 471 (1970), doi:10.1016/0022-5193(70)90109-8].

Each equation, \(\boldsymbol{a}_i \cdot \boldsymbol{x} = b_i\), where \(\boldsymbol{a}_i\) is the \(i\)th row of \(\boldsymbol{A}\), defines a hyperplane in \(n\)-dimensional space (a line when \(n = 2\), a plane when \(n = 3\)), to which \(\boldsymbol{a}_i\) is normal, and a solution of the system lies on all \(m\) hyperplanes. Starting from an initial guess, usually \(\boldsymbol{x}_0 = \boldsymbol{0}\), the algorithm projects its approximate solution, \(\boldsymbol{x}_k\), onto the hyperplane of one equation at a time. In its original, cyclic, form, it takes the equations in turn, \(i = (k \bmod m) + 1\), and

\[\boldsymbol{x}_{k+1} = \boldsymbol{x}_k + \frac{b_i - \boldsymbol{a}_i \cdot \boldsymbol{x}_k}{\lVert\boldsymbol{a}_i\rVert^2}\,\boldsymbol{a}_i.\]
Show derivationHide derivation

The projection of \(\boldsymbol{x}_k\) onto the hyperplane is the point of the hyperplane nearest to it, which is reached by a step along the normal, \(\boldsymbol{x}_{k+1} = \boldsymbol{x}_k + t\boldsymbol{a}_i\). This point lies on the hyperplane if \(\boldsymbol{a}_i \cdot \boldsymbol{x}_{k+1} = b_i\), that is, if

\[\boldsymbol{a}_i \cdot \boldsymbol{x}_k + t\lVert\boldsymbol{a}_i\rVert^2 = b_i,\]

which gives \(t = (b_i - \boldsymbol{a}_i \cdot \boldsymbol{x}_k)/\lVert\boldsymbol{a}_i\rVert^2\).

Each step satisfies one equation exactly, generally at the expense of the others. It needs only one row of \(\boldsymbol{A}\) and \(O(n)\) arithmetic operations, which suits the method to large, sparse systems, such as those of tomography. If the system has a solution, \(\boldsymbol{x}\), no step takes the approximation further from it: the step, \(\boldsymbol{x}_{k+1} - \boldsymbol{x}_k\), is parallel to \(\boldsymbol{a}_i\), and \(\boldsymbol{x}_{k+1} - \boldsymbol{x}\) lies within the hyperplane, since both \(\boldsymbol{x}_{k+1}\) and \(\boldsymbol{x}\) satisfy equation \(i\). The two vectors are therefore at right angles and, by Pythagoras' theorem,

\[\lVert\boldsymbol{x}_k - \boldsymbol{x}\rVert^2 = \lVert\boldsymbol{x}_{k+1} - \boldsymbol{x}\rVert^2 + \lVert\boldsymbol{x}_{k+1} - \boldsymbol{x}_k\rVert^2.\]

Every step adds a multiple of a row of \(\boldsymbol{A}\) to the approximation, and so approximations that start from \(\boldsymbol{x}_0 = \boldsymbol{0}\) stay in the space spanned by the rows: for an under-determined system, which has infinitely many solutions, the algorithm converges to the solution of least norm.

Two unknowns

When \(\boldsymbol{x}\) has two components, \(x\) and \(y\), the hyperplanes are lines, and the steps can be drawn in the plane. The system of four equations

\[\begin{pmatrix} -4 & 1 \\ 2 & \frac{1}{2} \\ 3 & \frac{3}{2} \\ 0 & 1 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} -2 \\ 3 \\ 6 \\ 2 \end{pmatrix}\]

is over-determined (it has more equations than unknowns) but consistent: its four lines meet at one point, \((x, y) = (1, 2)\), which is its solution. The function kaczmarz, from the program listed at the end of this post, implements the algorithm, and returns every approximation, the last of which is the solution:

python
import numpy as np

def kaczmarz(A, b, order="cyclic", tol=1e-6, max_steps=10000, rng=None):
    """Solve Ax = b by Kaczmarz's algorithm, starting from x = 0.

    The rows of A are taken in turn (order="cyclic"), at random with
    probabilities proportional to their squared norms (order="random"), or in
    a new random order in each pass through them (order="shuffled"); rng is a
    NumPy random Generator, or a seed for one. The iteration stops when x is
    closer than tol to the hyperplane of every equation, a_i . x = b_i, or
    after max_steps steps. Returns the array of approximate solutions x_0,
    x_1, ..., of which the last is the solution.
    """
    m, n = A.shape
    rng = np.random.default_rng(rng)
    norms2 = np.sum(A**2, axis=1)  # the squared norm of each row
    norms = np.sqrt(norms2)
    x = np.zeros(n)
    xs = [x]
    for k in range(max_steps):
        if order == "cyclic":
            i = k % m
        elif order == "random":
            i = rng.choice(m, p=norms2 / norms2.sum())
        elif order == "shuffled":
            if k % m == 0:
                rows = rng.permutation(m)
            i = rows[k % m]
        else:
            raise ValueError(f"Unknown order: {order}")
        x = x + (b[i] - A[i] @ x) / norms2[i] * A[i]
        xs.append(x)
        # The distances from the hyperplanes. Checking them costs as much as
        # m steps: a program for large systems would check once in each pass.
        if np.max(np.abs(A @ x - b) / norms) < tol:
            break
    return np.array(xs)

A = np.array([[-4, 1], [2, 0.5], [3, 1.5], [0, 1]])
b = np.array([-2, 3, 6, 2])
xs = kaczmarz(A, b)
print(f"{len(xs) - 1} steps to x = {xs[-1]}")
Output
28 steps to x = [1.00000056 2.        ]

The iteration stops when the approximation is closer than \(10^{-6}\) to every line; the distance of \(\boldsymbol{x}_k\) from the hyperplane of equation \(i\) is \(|\boldsymbol{a}_i \cdot \boldsymbol{x}_k - b_i|/\lVert\boldsymbol{a}_i\rVert\). The test uses the whole of \(\boldsymbol{A}\), at the cost of \(m\) steps, and so a program for a large system would make it only once in each pass through the equations.

Four lines cross at the point (1, 2): the line −4x + y = −2 rises steeply to the right, the lines 2x + y/2 = 3 and 3x + 3y/2 = 6 fall steeply to the right, and the line y = 2 is horizontal. A path of straight steps starts at the origin, steps onto each line in turn at right angles, rises vertically from (1.84, 0.32) to (1.84, 2), moves left to (1.05, 2.2) and closes in on (1, 2) in smaller loops.
The path of the cyclic order: \(\boldsymbol{x}_1\) is the projection of \(\boldsymbol{x}_0 = \boldsymbol{0}\) onto the line of the first equation, \(\boldsymbol{x}_2\) is the projection of \(\boldsymbol{x}_1\) onto the line of the second, and so on. From \(\boldsymbol{x}_9\) on, the approximations crowd around the solution, \((1, 2)\). The axes have equal scales, so that each step meets its line at right angles.

In two dimensions, the progress of each step follows from the angles between the lines. The lines all pass through the solution, and the projection of a point on one line onto another, at an angle \(\theta\) to it, multiplies the point's distance from the solution by \(|\cos\theta|\). The angles between successive lines are \(28.1^\circ\) (from the first line to the second), \(12.5^\circ\), \(63.4^\circ\) and \(76.0^\circ\) (from the fourth back to the first), and so each pass through the equations after the first multiplies the distance by

\[\cos 28.1^\circ \cos 12.5^\circ \cos 63.4^\circ \cos 76.0^\circ = 0.0934.\]

The second and third lines are nearly parallel, and the step between them makes little progress: \(\boldsymbol{x}_3\) is only 2 per cent closer to the solution than \(\boldsymbol{x}_2\). Most of the progress comes from the steps onto and off the fourth line, which is nearly perpendicular to the others. A pass of the cyclic order is a map of the plane into itself whose only fixed point is the solution, and the algorithm iterates this map, just as the post on the Dottie number iterates the cosine function.

Random order

Strohmer and Vershynin proposed taking the equations in random order, choosing equation \(i\) at each step with a probability proportional to the squared norm of its row,

\[p_i = \frac{\lVert\boldsymbol{a}_i\rVert^2}{\lVert\boldsymbol{A}\rVert_\mathrm{F}^2},\]

where \(\lVert\boldsymbol{A}\rVert_\mathrm{F}\), the Frobenius norm of \(\boldsymbol{A}\), is the square root of the sum of the squares of its elements. They proved that the expected squared error of this randomised Kaczmarz algorithm falls exponentially [T. Strohmer and R. Vershynin, Journal of Fourier Analysis and Applications 15, 262 (2009), doi:10.1007/s00041-008-9030-4]:

\[\mathrm{E}\,\lVert\boldsymbol{x}_k - \boldsymbol{x}\rVert^2 \le \left(1 - \frac{1}{\kappa^2}\right)^k \lVert\boldsymbol{x}_0 - \boldsymbol{x}\rVert^2, \qquad \kappa = \frac{\lVert\boldsymbol{A}\rVert_\mathrm{F}}{\sigma_\mathrm{min}},\]

where \(\sigma_\mathrm{min}\) is the smallest singular value of \(\boldsymbol{A}\). The rate depends on this scaled condition number, \(\kappa\), but not on the number of equations, nor on their order. For the system above, \(\kappa = 2.76\), and so the bound falls by a factor of 0.868 at each step. With order="random", the function kaczmarz takes the equations in this order:

The same four lines. The path starts at the origin, steps onto the line 3x + 3y/2 = 6 at (1.6, 0.8), and zig-zags upwards between this line and −4x + y = −2, in steps of decreasing length, to (1.12, 1.77). A step onto 2x + y/2 = 3 and, at the 13th step, one onto the horizontal line y = 2 bring it to within 0.06 of the solution, (1, 2), around which its remaining 73 steps crowd.
A run of the random order, which meets the tolerance after 86 steps, close to the median of 82 steps over 1000 runs.

For this system, the random order is about three times slower than the cyclic order. Its probabilities are 0.507, 0.127, 0.336 and 0.030, and so 84 per cent of its steps project onto the first or third line, between which the path zig-zags towards the solution, each step multiplying the distance by only \(\cos 40.6^\circ = 0.759\). The fourth line, which gives the cyclic order most of its progress, is chosen in only 3 per cent of the steps. In 39 per cent of the steps (\(\sum_i p_i^2 = 0.387\)), the equation is the same as that of the step before, and the step does nothing, since the approximation already lies on its line. The probabilities depend on the scale of each equation, which has no effect on its line: dividing the first equation by 4 would leave its line where it is, but reduce its weight, \(\lVert\boldsymbol{a}_1\rVert^2\), from 17 to \(\frac{17}{16}\).

Dividing each equation by the norm of its row makes the probabilities equal. Another order, the shuffled order, takes the equations in a new random order in each pass, so that no equation is taken twice within a pass. Over 1000 runs of each:

python
rng = np.random.default_rng(1907)
w = 1 / np.linalg.norm(A, axis=1)  # the reciprocal of the norm of each row
for label, AA, bb, order in (
        ("Random", A, b, "random"),
        ("Random, equal probabilities", A * w[:, None], b * w, "random"),
        ("Shuffled", A, b, "shuffled")):
    steps = [len(kaczmarz(AA, bb, order, rng=rng)) - 1 for _ in range(1000)]
    print(f"{label}: {np.mean(steps):.1f} steps on average")
Output
Random: 81.8 steps on average
Random, equal probabilities: 30.0 steps on average
Shuffled: 23.8 steps on average

With equal probabilities, the random order is nearly as fast as the cyclic order, and the shuffled order, which also avoids repeated steps, is faster than both. The errors of the four orders after each step are compared below. For the random orders, the figure shows the median error of 1000 runs, which represents a typical run better than the mean, since a few runs linger between nearly parallel lines.

Error on a logarithmic scale, from 10⁻⁹ to 10, against step, from 0 to 30. All the curves start at 2.24. The bound falls slowly, to 0.27 at step 30, and the random order's median error to 0.011. The cyclic order's error falls in a series of steps, to 1.2 × 10⁻⁷ at step 30; the median errors with equal probabilities and in shuffled order fall smoothly, to 7.4 × 10⁻⁷ and 1.2 × 10⁻⁸.
The error, \(\lVert\boldsymbol{x}_k - \boldsymbol{x}\rVert\), after each step of the cyclic order, and the median errors of 1000 runs of the random order, with probabilities proportional to the squared norms of the rows and with equal probabilities, and of the shuffled order. The dashed line is Strohmer and Vershynin's bound on the root-mean-square error of the random order.

Nearly parallel equations

The random order pays off when the cyclic order takes nearly parallel equations one after another. In tomography, for example, projections at neighbouring angles give nearly parallel hyperplanes, and the order in which ART takes the projections has a large effect on its speed [G. T. Herman and L. B. Meyer, IEEE Transactions on Medical Imaging 12, 600 (1993), doi:10.1109/42.241889]. In an extreme example, the lines of \(m\) equations pass through one point like the spokes of a wheel, at angles that increase by \(\pi/m\) from one equation to the next. Each step of the cyclic order then multiplies the distance from the solution by \(\cos(\pi/m)\), and each pass by

\[\cos^m\frac{\pi}{m} \approx \exp\left(-\frac{\pi^2}{2m}\right),\]

which approaches 1 as \(m\) increases. The random order makes larger turns: the geometric mean of \(|\cos\theta|\) for angles \(\theta\) distributed uniformly is \(\frac{1}{2}\), and so a random step typically halves the distance. The function fan in the program builds such a system, with its lines through the point \((1, 2)\):

Two panels, each with 13 lines through (1, 2) like the spokes of a wheel. Left: from the origin, the path steps to (1, 0) and spirals anticlockwise around (1, 2), crossing each spoke at right angles, in five turns whose radius shrinks slowly, from 2 to 0.3. Right: the path zig-zags from the origin across the lower spokes, with steps that turn through large angles, and reaches (1, 2) in 19 steps.
Thirteen lines through \((1, 2)\), at intervals of \(180^\circ/13\): the first five passes of the cyclic order (left), and a run of the random order, which meets the tolerance after 19 steps (right).

With 13 lines, the cyclic order needs 493 steps (38 passes) to meet the tolerance, and the random order 24.1 on average; with 51 lines, the cyclic order needs 7,644 steps, and the random order 22.7. The numbers of lines are odd because, with an even number, each line has a perpendicular partner, a projection onto which lands on the solution at once, and this flatters the random order: with 12 lines, it needs only 12.2 steps on average.

Inconsistent systems

An over-determined system rarely has a solution in practice: errors in the measurements that make up \(\boldsymbol{b}\) move the lines so that they no longer meet at a point. Adding the errors \((0.3, -0.2, 0.25, -0.15)\) to the elements of \(\boldsymbol{b}\) above gives such a system, and the approximations of Kaczmarz's algorithm then cannot converge, since no point lies on all four lines. In cyclic order, they settle into a limit cycle of four points, one on each line. In random order, they wander for ever, but their expected value converges: the expected step,

\[\mathrm{E}\,(\boldsymbol{x}_{k+1} - \boldsymbol{x}_k) = \sum_{i=1}^m p_i \frac{b_i - \boldsymbol{a}_i \cdot \boldsymbol{x}_k}{\lVert\boldsymbol{a}_i\rVert^2}\,\boldsymbol{a}_i = \frac{\boldsymbol{A}^\mathsf{T}(\boldsymbol{b} - \boldsymbol{A}\boldsymbol{x}_k)}{\lVert\boldsymbol{A}\rVert_\mathrm{F}^2},\]

is a step of gradient descent on \(\frac{1}{2}\lVert\boldsymbol{A}\boldsymbol{x} - \boldsymbol{b}\rVert^2\), and so the expected value converges to the least-squares solution, which minimises \(\lVert\boldsymbol{A}\boldsymbol{x} - \boldsymbol{b}\rVert\). The randomised algorithm is, in fact, a form of stochastic gradient descent [D. Needell, N. Srebro and R. Ward, Mathematical Programming 155, 549 (2016), doi:10.1007/s10107-015-0864-7], and Needell showed that it approaches the solution of the system without errors as quickly as before, but only to within a distance proportional to the errors [D. Needell, BIT Numerical Mathematics 50, 395 (2010), doi:10.1007/s10543-010-0265-5].

The four lines no longer meet at a point: five of their crossings lie between (0.89, 1.85) and (0.98, 2.21), and the nearly parallel second and third lines cross outside the figure, at (0.72, 2.73). The limit cycle is a quadrilateral with corners at (0.90, 1.90), (0.92, 1.90), (1.09, 1.99) and (1.09, 1.85), around the weighted least-squares solution, (0.976, 1.914). The random approximations lie along the lines, most of them above the cycle, around the least-squares solution, (0.965, 2.106).
The system with errors in \(\boldsymbol{b}\): the limit cycle of the cyclic order (the quadrilateral), 2000 approximations of the random order (small dots), with its path through the last 100 of them, and the least-squares solutions of the system (×) and of the system with each equation divided by the norm of its row (+).

The random approximations lie on the lines, since each lies on the line onto which it was last projected, and most of them lie on the first and third lines, whose probabilities are the largest. Under-relaxation, which multiplies each step by a factor \(\lambda < 1\), makes the cyclic order converge: as \(\lambda\) decreases, the limit cycle shrinks onto the least-squares solution of the system with each equation divided by the norm of its row [Y. Censor, P. P. B. Eggermont and D. Gordon, Numerische Mathematik 41, 83 (1983), doi:10.1007/BF01396307]. This weighted least-squares solution minimises the sum of the squared distances from the lines, \(\sum_i (\boldsymbol{a}_i \cdot \boldsymbol{x} - b_i)^2/\lVert\boldsymbol{a}_i\rVert^2\), and generally differs from the least-squares solution, which minimises the sum of the squared residuals, \(\sum_i (\boldsymbol{a}_i \cdot \boldsymbol{x} - b_i)^2\).

Code

The program kaczmarz.py draws the figures of this post, in Matplotlib's default style, and prints the numbers of steps of the runs that they show.

kaczmarz.py
"""Kaczmarz's algorithm for the solution of a system of linear equations,
Ax = b, with plots of the paths of its approximate solutions for systems of two
unknowns: a consistent system in cyclic and random order, a fan of lines
through one point, and the first system with errors in b."""

import matplotlib.pyplot as plt
import numpy as np

# Four equations in two unknowns, whose lines meet at (x, y) = (1, 2).
A = np.array([[-4, 1], [2, 0.5], [3, 1.5], [0, 1]])
b = np.array([-2, 3, 6, 2])
SOLUTION = np.array([1, 2])
# Errors in b that make the system inconsistent.
ERRORS = np.array([0.3, -0.2, 0.25, -0.15])
SEED = 1907  # for the random orders, so that every run gives the same results


def kaczmarz(A, b, order="cyclic", tol=1e-6, max_steps=10000, rng=None):
    """Solve Ax = b by Kaczmarz's algorithm, starting from x = 0.

    The rows of A are taken in turn (order="cyclic"), at random with
    probabilities proportional to their squared norms (order="random"), or in
    a new random order in each pass through them (order="shuffled"); rng is a
    NumPy random Generator, or a seed for one. The iteration stops when x is
    closer than tol to the hyperplane of every equation, a_i . x = b_i, or
    after max_steps steps. Returns the array of approximate solutions x_0,
    x_1, ..., of which the last is the solution.
    """
    m, n = A.shape
    rng = np.random.default_rng(rng)
    norms2 = np.sum(A**2, axis=1)  # the squared norm of each row
    norms = np.sqrt(norms2)
    x = np.zeros(n)
    xs = [x]
    for k in range(max_steps):
        if order == "cyclic":
            i = k % m
        elif order == "random":
            i = rng.choice(m, p=norms2 / norms2.sum())
        elif order == "shuffled":
            if k % m == 0:
                rows = rng.permutation(m)
            i = rows[k % m]
        else:
            raise ValueError(f"Unknown order: {order}")
        x = x + (b[i] - A[i] @ x) / norms2[i] * A[i]
        xs.append(x)
        # The distances from the hyperplanes. Checking them costs as much as
        # m steps: a program for large systems would check once in each pass.
        if np.max(np.abs(A @ x - b) / norms) < tol:
            break
    return np.array(xs)


def fan(m, point):
    """Return A and b for a system of m equations whose lines pass through
    point, at angles that increase by pi/m from one equation to the next."""
    theta = np.pi * np.arange(m) / m
    A = np.column_stack((np.cos(theta), np.sin(theta)))
    return A, A @ point


def errors(A, b, solution, order, n_steps, n_runs=1, rng=None):
    """Return the distances from solution of the approximations x_0, x_1, ...,
    x_{n_steps} in each of n_runs runs of Kaczmarz's algorithm, as an array
    with one row for each run."""
    rng = np.random.default_rng(rng)
    return np.array([np.linalg.norm(kaczmarz(A, b, order, tol=0,
                                             max_steps=n_steps, rng=rng)
                                    - solution, axis=1)
                     for _ in range(n_runs)])


def plot_system(ax, A, b, xs, lims):
    """Plot the line a_i . x = b_i of each equation of a system of two
    unknowns, and the path xs of Kaczmarz's algorithm, with equal scales on
    the axes, so that the steps meet the lines at right angles, and with the
    limits lims = (x0, x1, y0, y1)."""
    for ai, bi in zip(A, b):
        p = bi / (ai @ ai) * ai  # the point of the line nearest the origin
        ax.axline(p, p + (-ai[1], ai[0]), c="C0", lw=1)
    ax.plot(*xs.T, "o-", c="k", ms=3, lw=1)
    ax.set_aspect("equal")
    ax.axis(lims)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")


if __name__ == "__main__":
    # The paths of the cyclic and random orders.
    fig, axes = plt.subplots(ncols=2, figsize=(10, 5), layout="constrained")
    for ax, order in zip(axes, ("cyclic", "random")):
        xs = kaczmarz(A, b, order, rng=SEED)
        print(f"{order}: {len(xs) - 1} steps to x = {xs[-1]}")
        plot_system(ax, A, b, xs, (-0.5, 2.5, -0.5, 2.5))
        ax.set_title(f"{order.capitalize()} order")

    # The error of the cyclic order, the median errors of 1000 runs of each
    # random order (the random order of the system with each equation divided
    # by the norm of its row chooses the rows with equal probabilities), and
    # Strohmer and Vershynin's bound on the root-mean-square error of the
    # random order.
    n_steps = 30
    k = np.arange(n_steps + 1)
    w = 1 / np.linalg.norm(A, axis=1)
    fig, ax = plt.subplots(layout="constrained")
    for label, AA, bb, order, n_runs in (
            ("cyclic", A, b, "cyclic", 1),
            ("random", A, b, "random", 1000),
            ("equal probabilities", A * w[:, None], b * w, "random", 1000),
            ("shuffled", A, b, "shuffled", 1000)):
        e = errors(AA, bb, SOLUTION, order, n_steps, n_runs, rng=SEED)
        ax.plot(k, np.median(e, axis=0), label=label)
    sigma = np.linalg.svd(A, compute_uv=False)  # the singular values of A
    kappa = np.linalg.norm(A) / sigma[-1]
    print(f"kappa = {kappa:.2f}")
    ax.plot(k, np.linalg.norm(SOLUTION) * (1 - 1 / kappa**2)**(k / 2), "k--",
            label="bound")
    ax.set_yscale("log")
    ax.set_ylim(1e-9, 10)
    ax.set_xlabel("Step, $k$")
    ax.set_ylabel(r"Error, $\Vert\mathbf{x}_k - \mathbf{x}\Vert$")
    ax.legend()

    # A fan of 13 lines through (1, 2), in cyclic order (its first five
    # passes) and in random order.
    F, g = fan(13, SOLUTION)
    fig, axes = plt.subplots(ncols=2, figsize=(10, 5), layout="constrained")
    for ax, order in zip(axes, ("cyclic", "random")):
        xs = kaczmarz(F, g, order, rng=SEED)
        print(f"Fan, {order}: {len(xs) - 1} steps")
        plot_system(ax, F, g, xs[:66], (-1.4, 3.4, -0.4, 4.4))
        ax.set_title(f"{order.capitalize()} order")

    # The system with errors in b: the last pass of the cyclic order, 2000
    # steps of the random order, and the least-squares solutions of the
    # system (x) and of the system with each equation divided by the norm of
    # its row (+).
    be = b + ERRORS
    x_ls = np.linalg.lstsq(A, be)[0]
    x_wls = np.linalg.lstsq(A * w[:, None], be * w)[0]
    print(f"Least-squares solution: {x_ls}; weighted: {x_wls}")
    fig, ax = plt.subplots(layout="constrained")
    plot_system(ax, A, be, kaczmarz(A, be, tol=0, max_steps=400)[-5:],
                (0.6, 1.4, 1.6, 2.4))
    xs = kaczmarz(A, be, "random", tol=0, max_steps=2000, rng=SEED)
    ax.plot(*xs.T, ".", c="0.5", ms=2, zorder=0)
    ax.plot(*x_ls, "kx", ms=10)
    ax.plot(*x_wls, "k+", ms=10)
    plt.show()
kaczmarz.py
The program

Comments

Leave a comment

Optional, and never shown: only the moderator sees it.

Comments are written in Markdown (code between ``` lines) and appear once approved. Your name and comment are published; your email address, if you give one, is seen only by the moderator.