%matplotlib inline
from functools import wraps
import numpy as np
import matplotlib.pyplot as pltOne thing we want to be able to do compare two different algorithms that compute the same result.
Many numerical algorithms operate through some sort of iterative process, where we get better and better approximations to the answer at each iteration.
One example of this is Newton’s method for root finding. A root of a continuous function is a value so that .
Given a function , we would like to find some root . Newton’s method computes a sequence of iterations
def newton_root(f, fp, x0=1, tol=1e-4, max_iter=1e3):
"""
numerically approximate a root of f using Newton's method
inputs:
f - function
fp - derivative of function f
x0 - starting point (default 1)
tol - tolerance for terminating the algorithm (default 1e-4)
max_iter - maximum number of iterations (default 1e3)
returns:
x - the root
iters = a list of all x visited
fs - f(x) for each iteration
"""
x = x0
fx = f(x0)
n_iter = 0
iters = []
fs = []
while (abs(fx) > tol and n_iter <= max_iter):
x = x - fx / fp(x)
fx = f(x)
n_iter = n_iter + 1
iters.append(x)
fs.append(fx)
return x, iters, fsThe idea is that the linear approximation of at is the line
The -intercept of the line would be at . Let’s look at an example
f = lambda x : x**2 - 2
fp = lambda x : 2*x
xmin, xmax = -2, 2
xs = np.linspace(xmin, xmax, 100)
x0 = 1
plt.plot(xs, f(xs), 'k-', label='f') # plot the function
plt.hlines(0, xmin, xmax, colors='gray', linestyles='dashed') # dashed line for y = 0
plt.scatter(x0, f(x0), c='k')
plt.text(x0 + 0.05, f(x0) - 0.1, r'$x_0$') # x0 label
x1 = x0 - f(x0)/fp(x0)
plt.plot(xs, fp(x0)*(xs - x1), 'k--', label='tangent')
plt.scatter(x1, 0, c='k')
plt.text(x1 + 0.05, -0.2, r'$x_1$') # x1 label
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.legend()
plt.show()f = lambda x : x**2 - 2
fp = lambda x : 2*x
x , ix, iy = newton_root(f, fp)
print(x)
print(f'Error is {x - np.sqrt(2)}')
x, ix, iy = newton_root(f, fp, x0=-1)
print(x)Another root finding algorithm is the bisection method. This operates by narrowing an interval which is known to contain a root. Assuming is continuous, we can use the intermediate value theorem. We know that if , and , there must be some so that . At each iteration, we narrow the interval by looking at the midpoint and then looking at the interval or the interval depending on which one contains a root based on the intermediate value theorem.
Exercise¶
Implement the bisection method as a recursive function.
## Your code here
def bisection_root_recursive(f, lb=-1, ub=1, tol=1e-4):
"""
search for a root of f between lower bound and upper bound
inputs:
f - function
lb - lower bound of interval containing root
ub - upper bound of interval containing root
tol - tolerance for deciding if we've found root i.e. |f(x)| < tol
assume f(lb) < 0 < f(ub)
returns:
x - root satisfying |f(x)| < tol
"""
passNotebook Cell
def bisection_root_recursive(f, lb=-1.0, ub=1.0, tol=1e-4):
"""
search for a root of f between lower bound and upper bound
inputs:
f - function
lb - lower bound of interval containing root
ub - upper bound of interval containing root
tol - tolerance for deciding if we've found root i.e. |f(x)| < tol
assume f(lb) < 0 < f(ub)
returns:
x - root satisfying |f(x)| < tol
"""
x = (lb + ub) / 2
fx = f(x)
if abs(fx) < tol:
return x
elif fx < 0:
return bisection_root_recursive(f, lb=x, ub=ub, tol=tol)
else:# fx > 0
return bisection_root_recursive(f, lb=lb, ub=x, tol=tol)
bisection_root_recursive(lambda x: x-1, 0, 5)Here’s a sequential implementation which keeps track of the iterates.
def bisection_root(f, lb=-1, ub=1, tol=1e-4):
"""
numerically approximate a root of f using bisection method
assume signs of f(inf), f(-inf) are different
inputs:
f - function
lb - lower bound of interval containing root
ub - upper bound of interval containing root
tol - tolerance for terminating the algorithm (default 1e-4)
returns
x - the root
iters = a list of all x visited
fs - f(x) for each iteration
"""
# first increase range until signs of f(lb), f(ub) are different
while f(lb) * f(ub) > 0:
lb *= 2
ub *= 2
iters = []
fs = []
# see if we found a root with one of our bounds
if abs(f(lb)) < tol:
return lb, iters, fs
if abs(f(ub)) < tol:
return ub, iters, fs
# make lb correspond to negative sign
if f(lb) > 0:
# swap upper and lower
lb, ub = ub, lb
while True:
x = (ub + lb)/2.0 # mean
iters.append(x)
fx = f(x)
fs.append(fx)
if abs(fx) < tol:
# found a root
return x, iters, fs
elif fx > 0:
# f(x) > 0
ub = x
else:
# f(x) < 0
lb = xf = lambda x : (x - 2)*(x + 3)*(x + 5)
x, ix, iy = bisection_root(f, lb = -10, ub = 10)
xLet’s test these two methods on the same function
f = lambda x : x**3 + 2*x**2 + 5*x + 1
fp = lambda x : 3*x**2 + 4*x + 5
tol = 1e-8
x_newton, iter_newton, f_newton = newton_root(f, fp, tol=tol)
x_bisect, iter_bisect, f_bisect = bisection_root(f, tol=tol)
print(f"Newton's method: {x_newton}")
print(f"Bisection method: {x_bisect}")
print(f"Diff: {np.abs(x_newton - x_bisect)}")Let’s see how many iterations each method performed
print(len(iter_newton))
print(len(iter_bisect))It looks like one algorithm is converging faster than the other - let’s track how close each iteration is to a root:
plt.semilogy(np.abs(f_newton), label="newton")
plt.semilogy(np.abs(f_bisect), label="bisection")
plt.legend()
plt.show()The below function comes from the section on convergence:
def estimate_q(eps):
"""
estimate rate of convergence q from sequence esp
"""
x = np.arange(len(eps) -1)
y = np.log(np.abs(np.diff(np.log(eps))))
line = np.polyfit(x, y, 1) # fit degree 1 polynomial
q = np.exp(line[0]) # find q
return qprint(estimate_q(np.abs(f_newton)))
print(estimate_q(np.abs(f_bisect)))experimentally, we see that the bisection converges linearly, and Newton’s method converges close to its theoretical guarantee of quadratically.
Exercise¶
Prove that the bisection method converges linearly.
Sketch of Answer
Let be the inital width of the interval that contains the root. The maximum distance to the root from either or is , so . At each step of the algorithm, we look at the midpoint, and reduce the length of the interval we are looking at by 2. This means . We now look at the ratio , so the algorithm converges linearly.
Note you would need to be a bit more careful with the ratio to really prove convergence.
An Application of Decorators¶
While Newton’s method converges faster, it required us to provide the derivative of the function we’re trying to find a root for. This might not always be easy to implement.
Instead, we might consider numerically approximating the derivative. Recall
We’ll use the symmetric definition
Let’s define a non-limit version
for fixed , if is sufficiently small, then near . is known as finite difference.
We can explicitly define a numerical derivative of a function via
def delta(f, h=1e-8):
def wrapper(x):
return (f(x + h) - f(x - h))/(2*h)
return wrapperf = lambda x : (x - np.sqrt(2))*np.exp(-x**2)
fp = delta(f)x_newton, iter_newton, f_newton = newton_root(f, fp, tol=1e-6)
x_newtonlen(iter_newton)we might also consider defining a decorator that returns from a function definition
from functools import wraps
def add_numerical_derivative(f, default_h=1e-8):
@wraps(f)
def wrapper(x, h=default_h):
ret = f(x)
deriv = (f(x + h) - f(x - h)) / (2*h)
return ret, deriv
return wrapper
@add_numerical_derivative
def f(x):
return (x - np.sqrt(2))*np.exp(-x**2)
f(0.5) # returns value, numerical derivativef(0.5, h=1e-7)Exercise¶
Estimate the rate of convergence for Newton’s method when we use a finite difference to approximate the derivative.
Does this change with the value of ?
f = lambda x : (x - np.sqrt(2))*np.exp(-x**2)
for h in np.logspace(-1,-14, 10):
print(f"h={h}")
fp = delta(f, h=h)
x_newton, iter_newton, f_newton = newton_root(f, fp, tol=1e-14)
print(f"num_iter={len(iter_newton)}")Root Finding in SciPy¶
scipy.optimize.fsolve
finds a root of a function starting from an initial guess x0. It calls the hybrd routine, a Newton-type method with safeguards for
when the plain Newton step goes astray. If you do not supply the derivative, fsolve approximates it
with finite differences.
from scipy.optimize import fsolve
f = lambda x : x**2 - 2
x = fsolve(f, 1)
print(x)
print(f'Error is {x - np.sqrt(2)}')fsolve always returns an array, even for a scalar equation. As with Newton’s method, the root
you get depends on the initial guess:
print(fsolve(f, 1), fsolve(f, -1))You can pass the derivative with fprime. With full_output=True, fsolve also returns a
dictionary info (number of function evaluations nfev, final value fvec, ...), an integer flag
ier that equals 1 on success, and a message. Here is the cubic from the comparison above:
f = lambda x : x**3 + 2*x**2 + 5*x + 1
fp = lambda x : 3*x**2 + 4*x + 5
x, info, ier, msg = fsolve(f, 1, full_output=True)
print(f"finite differences: x = {x}, {info['nfev']} evaluations of f, {msg}")
x, info, ier, msg = fsolve(f, 1, fprime=fp, full_output=True)
print(f"with fprime: x = {x}, {info['nfev']} evaluations of f, {info['njev']} of fp, {msg}")fsolve evaluated the derivative only once. After that it updates its approximation of the
derivative from the values of it computes anyway (a Broyden update), and re-evaluates it only when
progress stalls. So the finite-difference version costs only one extra evaluation of here.
Check the answer¶
fsolve does not raise an error when it fails. The function has no real root:
x = fsolve(lambda x : x**2 + 1, 1)
print(x, x**2 + 1)All we get is a RuntimeWarning, which is easy to miss, and a value that is not a root. With
full_output=True there is no warning at all; the failure only shows up in ier and in the residual:
x, info, ier, msg = fsolve(lambda x : x**2 + 1, 1, full_output=True)
print(f"ier = {ier}: {msg}")
print(f"residual f(x) = {info['fvec']}")fsolve stops when two consecutive iterates agree to a relative tolerance xtol (default about
), so it never tests directly. Its flag can also report a failure when the root
has in fact been found to round-off. The reliable check is to look at the residual yourself.