Many numerical algorithms are iterative: instead of computing the answer directly, they produce a sequence of approximations that get closer and closer to the true solution. Examples include Newton’s method for finding roots, gradient descent for optimization, and iterative solvers for linear systems.
We’ll let denote the true solution, and denote the th iterate of an algorithm. The error at iteration is
(if the are vectors, we use a norm instead: ). An algorithm converges if
Knowing that an algorithm converges is not enough to make it useful. An algorithm that needs 5 iterations to get 15 correct digits is very different from one that needs 1030 iterations. In this section, we’ll make “how fast” precise, look at concrete algorithms that converge at different speeds, and see how to measure the speed from experimental data.
Monitoring Convergence in Practice¶
In practice, we typically don’t know the value of (otherwise we wouldn’t need the algorithm). There are two common substitutes for the error:
Run the algorithm for iterations and treat the last iterate as the true solution, i.e. estimate . This is reasonable for much smaller than .
Monitor the difference between consecutive iterates, . If the algorithm is converging, then as well. A typical stopping criterion is to stop as soon as (absolute tolerance) or (relative tolerance).
In this class, we aren’t going to worry too much about proving that algorithms converge. However, we do want to be able to verify that an algorithm is converging, measure the rate of convergence, and compare two algorithms using experimental convergence data.
Rate of Convergence¶
There are a variety of ways to define the rate of convergence. The most common one compares the error at iteration to the error at iteration . We say that with order and rate if
In words: once is large enough, each iteration does roughly . The constant is also called the asymptotic error constant.
The most important cases have names:
| Name | Definition | What happens to the error |
|---|---|---|
| linear | and | multiplied by each iteration, so |
| superlinear | faster than linear with any rate ; this includes every order | |
| quadratic | ||
| cubic | ||
| sublinear | and | slower than linear, e.g. |
Larger values of indicate faster convergence. For the same , a smaller is faster.
A few remarks:
If and , the error grows. An order is also impossible for a sequence that converges to 0.
For , any is allowed, even , because .
The order and rate are asymptotic properties. They say nothing about the first few iterations, and it can take many iterations before an algorithm settles into its asymptotic behavior.
For some algorithms, the ratio has no limit, so they don’t fit the definition exactly. If the error is bounded by a sequence that converges linearly, e.g. , we still say the algorithm converges linearly. Bisection is an example (see below).
Counting Correct Digits¶
The easiest way to understand the order is to count digits. The quantity is roughly the number of correct decimal digits in : for example, means about 6 correct digits. Taking of gives
Linear (): . Each iteration adds a fixed number of correct digits. With we gain digits per iteration, so 16 digits (double precision) take about iterations. With we gain exactly one digit per iteration.
Quadratic (): . The number of correct digits roughly doubles each iteration: . Starting from one correct digit, we reach double precision in about 4 iterations.
Order : the number of correct digits is multiplied by about each iteration.
Sublinear: the number of digits gained per iteration goes to 0. For , getting 16 digits takes 1016 iterations.
Model Sequences¶
Let’s generate some model error sequences by running the recursion directly.
import numpy as np
import matplotlib.pyplot as plt# generates a linearly converging sequence: eps[k+1] = 0.5 * eps[k]
n = 50
mu = 0.5
q = 1
eps1 = [1.0]
for i in range(n):
eps1.append(mu * eps1[-1]**q)
# generates a quadratically converging sequence: eps[k+1] = 2 * eps[k]**2
n = 9
mu = 2.0
q = 2
eps2 = [0.2]
for i in range(n):
eps2.append(mu * eps2[-1]**q)
# generates a sublinearly converging sequence: eps[k] = 1/k
n = 50
eps3 = []
for k in range(1, n):
eps3.append(1.0/k)fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ax[0].semilogy(eps1, 'o-', label='linear')
ax[0].semilogy(eps2, 's-', label='quadratic')
ax[0].semilogy(eps3, '^-', label='sublinear')
ax[0].set_xlabel('k')
ax[0].set_ylabel(r"$\epsilon_k$")
ax[0].set_ylim(1e-16, 1e0)
ax[0].set_title("types of convergence (semilogy)")
ax[0].legend()
k = np.arange(1, len(eps3) + 1)
ax[1].loglog(k, eps3, '^-', color='C2', label=r'sublinear, $\epsilon_k = 1/k$')
ax[1].set_xlabel('k')
ax[1].set_ylabel(r"$\epsilon_k$")
ax[1].set_title("sublinear convergence (loglog)")
ax[1].legend()
plt.show()A
semilogyplot (log scale on the -axis only) shows against . Linear convergence gives , which is a straight line with slope . Superlinear convergence bends downward (it gets steeper and steeper), and sublinear convergence flattens out.If a sublinear sequence behaves like for some power . Then , which is a straight line with slope on a
loglogplot. Here , so .
Estimating the Order of Convergence¶
Now suppose we have a sequence of errors from an experiment, but we don’t know the theory. How can we measure ?
Local Estimates¶
If , then taking logarithms gives
Subtracting the same relation one step earlier () eliminates the unknown :
Each uses three consecutive errors, so we get one estimate per iteration, and we can watch the estimates settle down as grows.
def local_q(eps):
"""
local estimates q_k = log(eps[k+1]/eps[k]) / log(eps[k]/eps[k-1])
for k = 1, ..., len(eps) - 2
"""
r = np.diff(np.log(eps)) # r[k] = log(eps[k+1]) - log(eps[k])
return r[1:] / r[:-1]
print("Linear:", np.round(local_q(eps1[:8]), 4))
print("Quadratic:", np.round(local_q(eps2[:8]), 4))
print("Sublinear:", np.round(local_q(eps3[:8]), 4))Fitting a Line¶
Let . The relation above says , so grows (or shrinks) geometrically, and
So if we plot against , we should see a straight line with slope . The function below fits a line to these points using np.polyfit, and returns .
def estimate_q(eps):
"""
estimate rate of convergence q from sequence eps
"""
x = np.arange(len(eps) -1)
y = np.log(np.abs(np.diff(np.log(eps)))) # y[k] = log|r_k|
line = np.polyfit(x, y, 1) # fit degree 1 polynomial
q = np.exp(line[0]) # find q
return qprint(estimate_q(eps1)) # linear
print(estimate_q(eps2)) # quadratic
print(estimate_q(eps3)) # sublinearFor the model sequences, holds exactly, so we recover and exactly. For , the estimate is a bit below 1; we’ll come back to this in the exercises.
Practical Tips¶
Discard the pre-asymptotic phase. The order describes the behavior as . The first few iterates may behave differently (e.g. the error of the secant method increased in the first step).
Discard iterates at machine precision. In double precision, the error can’t get much below . Once it gets there, round-off error dominates and the ratios are meaningless.
Look at the plot first. A
semilogyplot of (or ) against tells you a lot at a glance: a straight line means linear, bending down means superlinear, and flattening out means sublinear (in which case try aloglogplot).is ambiguous. Check the rate to tell linear () from sublinear () convergence.
Exercises¶
Generate a converging sequence with , and estimate using the above methods.
Generate sublinear sequences with (as above) for lengths 50, 100, 500, 1000, 5000, and 10000. How does our estimate of change with the length of the sequence?
Solutions¶
Exercise 1.
# generates a sequence converging with order q = 1.5
n = 9
mu = 1.5
q = 1.5
eps4 = [0.2]
for i in range(n):
eps4.append(mu * eps4[-1]**q)
plt.semilogy(eps4, 'o-')
plt.xlabel('k')
plt.ylabel(r"$\epsilon_k$")
plt.title("q = {} convergence".format(q))
plt.show()
print("estimate_q:", estimate_q(eps4))
print("local_q: ", local_q(eps4))Exercise 2.
def gen_sublinear(n):
eps = []
for k in range(1,n):
eps.append(1.0/k)
return eps
ns = [50, 100, 500, 1000, 5000, 10000]
for n in ns:
eps = gen_sublinear(n)
print(n, estimate_q(eps))The estimate approaches 1 as the sequence gets longer, but slowly. For , we have , so . This is not a straight line in , so fitting a line gives a slope slightly below 0 (i.e. slightly below 1). The slope of flattens out as grows, so the fitted slope gets closer to 0 for longer sequences. This is another reason to use a loglog plot for sublinear sequences.