Module contents
Lesson 8 of 26Review 75 min

Nonlinear equations: bisection, Newton and robust methods

Solve f(x) = 0 by bisection, fixed points, Newton and secant, measuring their convergence orders. Study how Brent combines robustness and speed, and use Newton and Broyden for systems. Build a robust solver to reuse with implicit methods and sampling.

After this lesson you can

  • Implement bisection, fixed-point iteration, Newton’s method, secant and a safeguarded Brent-style method.
  • Estimate convergence order from iterates and use it to check an implementation.
  • Prove quadratic convergence of Newton’s method near a simple root.
  • Solve nonlinear systems with Newton’s method using analytic or finite-difference Jacobians, and with Broyden’s method.
  • Choose stopping criteria that account for root conditioning.

Before you start

Motivation: equations without explicit solutions

Almost any realistic model eventually needs a number defined only implicitly, such as a zero of a function you can evaluate but cannot invert:

  • Implied volatility. The market quotes an option at €2.31 and the Black–Scholes formula gives price C(σ)C(\sigma) for each volatility σ\sigma. Implied volatility solves C(σ)−2.31=0C(\sigma) - 2.31 = 0, and an options desk recomputes it for every option in its book whenever the market moves.
  • A circuit’s operating point. A diode in series with resistance RR and source VsV_s obeys Shockley’s equation Is (eV/VT−1)=(Vs−V)/RI_s\,(e^{V/V_T} - 1) = (V_s - V)/R. Several diodes and transistors give a nonlinear system, which SPICE solves in each DC analysis.
  • Kepler’s equation. A planet’s position on its elliptical orbit of eccentricity ee at time tt comes from eccentric anomaly EE, satisfying M=E−esin⁡EM = E - e\sin E with MM proportional to time. Kepler posed it in 1609; it has no closed-form solution and fast methods remain a research topic.
  • Every implicit integrator step. Implicit Euler advances yn+1=yn+h f(tn+1,yn+1)\vb{y}_{n+1} = \vb{y}_n + h\,\vb{f}(t_{n+1}, \vb{y}_{n+1}): the unknown appears on both sides. Each step requires solving a system G(y)=0\vb{G}(\vb{y}) = \vb{0} as large as the problem, explaining the cost of implicit methods, essential for stiff equations.

This dense review focuses on methods actually used. Every root finder must answer three questions: what does it guarantee (always find a root or only from nearby?), how fast (digits gained per evaluation?), and when should it stop (how do you know it is done?). Bisection best answers the first, Newton the second; the third depends more on root conditioning than method. Production methods such as Brent combine the first two. Finally you will build a robust safeguarded Newton solver, reused in implicit integrators and inverse transform sampling, where each sample requires solving F(x)=uF(x) = u.

Bisection: a guarantee

If ff is continuous on [a,b][a, b] and f(a)f(a) and f(b)f(b) have opposite signs, the intermediate value theorem guarantees at least one root inside. Bisection uses that guarantee without further assumptions: evaluate ff at midpoint mm, keep the half with a sign change and repeat.

The proof is one-line induction: the chosen half has a sign change, hence a root, and half the length. Notice what is absent: derivatives, smoothness and a nearby starting point. Also absent is ff: iteration count is the same for cos⁡x−x\cos x - x as for a fiendish function. This is both strength and limit. Each evaluation gains exactly one bit, log⁡102≈0.301\log_{10} 2 \approx 0.301 decimal digits. In convergence-order terminology, bisection converges R-linearly at rate 1/21/2: midpoint error need not decrease every step, but is bounded by half the interval length, which does halve each step.

Three details separate textbook bisection from a floating-point implementation:

  1. Compute the midpoint as a+(b−a)/2a + (b - a)/2. Formula (a+b)/2(a + b)/2 overflows if aa and bb are large and same-signed (near 1030810^{308} their sum is already infinite), while b−ab - a does not, and a+(b−a)/2a + (b - a)/2 never leaves [a,b][a, b].
  2. Compare signs rather than multiplying. f(a) f(m)f(a)\,f(m) can give 00 through underflow when both values are small, silently defeating test f(a)f(m)<0f(a)f(m) < 0.
  3. Stop when mm equals an endpoint. No floating-point number remains between aa and bb and continuing changes nothing. Without tolerance this happens after about fifty iterations on an interval like [2,3][2, 3]: its length reaches one ulp.
[ ]Bisection from scratchBrowser
import math

def biseccion(f, a, b, xtol=0.0, maxiter=200):
    """Bisección que registra los iterados. Devuelve (x, iterados)."""
    fa, fb = f(a), f(b)
    if fa == 0:
        return a, [a]
    if fb == 0:
        return b, [b]
    if (fa < 0) == (fb < 0):
        raise ValueError("f(a) y f(b) deben tener signos opuestos")
    xs = []
    for _ in range(maxiter):
        m = a + (b - a) / 2                  # nunca sale de [a, b]
        if m == a or m == b or b - a <= xtol:
            break                            # no queda ningún doble entre a y b, o ya basta
        fm = f(m)
        xs.append(m)
        if fm == 0:
            break
        if (fm < 0) == (fa < 0):             # comparar signos, no multiplicar
            a, fa = m, fm
        else:
            b = m
    return xs[-1], xs

f = lambda x: x**3 - 2 * x - 5               # la ecuación con la que Newton presentó su método
x, xs = biseccion(f, 2.0, 3.0)
print(f"raíz = {x!r}   iteraciones hasta agotar los dobles: {len(xs)}")
x6, xs6 = biseccion(f, 2.0, 3.0, xtol=1e-6)
print(f"con xtol = 1e-6: {len(xs6)} iteraciones; la fórmula da {math.ceil(math.log2(1 / 1e-6))}")
print("ulp(2) =", math.ulp(2.0), "= 2^", int(math.log2(math.ulp(2.0))))

# por qué no multiplicar los signos
fa, fm = 1e-200, -1e-200
print("\nf(a) * f(m) =", fa * fm, "  ¿< 0?", fa * fm < 0, "  comparando signos:", (fa < 0) != (fm < 0))

The loop without tolerance stops when the interval shrinks to the ulp of numbers near [2,3][2, 3], namely 2−512^{-51}. With xtol = 1e-6 the count matches the formula. Multiplying two values of size 10−20010^{-200} gives −0-0, which is not negative: bisection multiplying signs would silently choose the wrong half.

Conditioning of a root

How far is refinement meaningful? Suppose instead of ff the computer evaluates f~=f+δ\tilde f = f + \delta with ∣δ(x)∣≤εf\abs{\delta(x)} \le \varepsilon_f (rounding error evaluating ff, or simulation noise). If x∗x^* is a simple root, f(x∗+Δx)≈f′(x∗) Δxf(x^* + \Delta x) \approx f'(x^*)\,\Delta x, so f~\tilde f vanishes near x∗+Δxx^* + \Delta x with

∣Δx∣≈εf∣f′(x∗)∣.\abs{\Delta x} \approx \frac{\varepsilon_f}{\abs{f'(x^*)}}.

The number 1/∣f′(x∗)∣1/\abs{f'(x^*)} is the absolute condition number of the problem “root of ff”, as in lesson 3: how far the answer moves per unit perturbation of the data, here the function itself. A root where ff crosses the axis almost horizontally is ill-conditioned.

If the root has multiplicity mm, meaning f(x∗)=⋯=f(m−1)(x∗)=0≠f(m)(x∗)f(x^*) = \cdots = f^{(m-1)}(x^*) = 0 \ne f^{(m)}(x^*), the first surviving Taylor term is f(m)(x∗) Δxm/m!f^{(m)}(x^*)\,\Delta x^m/m! and

∣Δx∣≈(m! εf∣f(m)(x∗)∣)1/m.\abs{\Delta x} \approx \left(\frac{m!\,\varepsilon_f}{\abs{f^{(m)}(x^*)}}\right)^{1/m}.

The mm-th root is devastating: perturbation 10−1410^{-14} moves a seventh-order root by order 10−210^{-2}. This is not an algorithm defect. The problem itself contains no more information on the root’s location.

InteractiveA multiple root's noise cloud
Vertical axis: f(x) in units of 10⁻¹³. Points are computed with Horner from the 8 coefficients of expanded (x − 1)^7.
  • value computed in float64
  • exact value (x−1)m(x - 1)^m
  • noise cloud radius
  • ∣f∣≤tol|f| \le \mathrm{tol} and accepted xx values
7
0.015
1.0·10⁻¹⁰
f(x)=(x−1)7f(x) = (x - 1)^{7}
Maximum rounding noise εf\varepsilon_f near 17.1·10⁻¹⁵
Measured cloud radius (incorrect computed sign)0.00855
Prediction εf1/m\varepsilon_f^{1/m}0.00953
∣f∣≤tol|f| \le \mathrm{tol} accepts ∣x−1∣|x - 1| up to tol1/m\mathrm{tol}^{1/m}0.0373
Root of multiplicity 7: no floating-point calculation can locate it more accurately than ≈0.00855\approx 0.00855, and ∣f∣≤1⋅10−10|f| \le 1·10⁻¹⁰ accepts any xx at distance 0.0373.
Points are float64 values of (x−1)m(x - 1)^m computed by Horner from expanded coefficients, as a program knowing only the polynomial does; the curve is exact. For m=1m = 1 they agree. Increase mm and zoom in: a cloud of radius εf1/m\varepsilon_f^{1/m} appears where computed sign is random, and no method can locate the root inside it. Then move tolerance: the red band shows all xx accepted by a ∣f(x)∣≤tol|f(x)| \le \mathrm{tol} criterion.

The figure computes this live; the cell repeats it with NumPy using the same IEEE doubles:

[ ]Measuring cloud radiusBrowser
import numpy as np
from math import comb

for m in range(2, 9):
    coef = [comb(m, k) * (-1)**k for k in range(m + 1)]     # (x - 1)^m desarrollado
    R = 3 * (2 * m * 2.0**-53 * 2**m) ** (1 / m)             # una ventana holgada alrededor de 1
    x = np.linspace(1 - R, 1 + R, 8001)
    fx = np.zeros_like(x)
    for c in coef:                                            # Horner
        fx = fx * x + c
    exacta = (x - 1) ** m
    ruido = np.abs(fx - exacta).max()
    malo = (np.sign(fx) != np.sign(exacta)) & (exacta != 0)
    radio = np.abs(x[malo] - 1).max()
    print(f"m = {m}:  ruido {ruido:.1e}   radio medido {radio:.2e}   ruido^(1/m) = {ruido ** (1 / m):.2e}   "
          f"|f| <= 1e-10 acepta |x - 1| <= {1e-10 ** (1 / m):.3f}")

With m=7m = 7 Horner noise near x=1x = 1 is about 7×10−157\times 10^{-15}, and the computed sign is wrong up to 0.00850.0085 from the root, of the order predicted by εf1/7≈0.0095\varepsilon_f^{1/7} \approx 0.0095; other multiplicities agree similarly. The second reading matters for code: with m=7m = 7, condition ∣f(x)∣≤10−10\abs{f(x)} \le 10^{-10} holds throughout ∣x−1∣≤10−10/7≈0.037\abs{x - 1} \le 10^{-10/7} \approx 0.037. A tiny residual says nothing about distance to an ill-conditioned root. We revisit this under stopping criteria.

Fixed-point iteration

Every equation f(x)=0f(x) = 0 can be rewritten as x=g(x)x = g(x) in many ways, allowing fixed-point iteration xk+1=g(xk)x_{k+1} = g(x_k). Kepler’s equation is already written this way, E=M+esin⁡EE = M + e\sin E, and Newton is also a fixed-point iteration, with g(x)=x−f(x)/f′(x)g(x) = x - f(x)/f'(x). This theory explains the speed of almost every method in the lesson.

The Banach fixed-point theorem gives global convergence when gg is contractive on a closed interval mapped into itself. In practice that is rare, but a local result holds:

Proof

By continuity of g′g' there are δ>0\delta > 0 and L<1L < 1 with ∣g′(x)∣≤L\abs{g'(x)} \le L on I=[x∗−δ,x∗+δ]I = [x^* - \delta, x^* + \delta]. If xk∈Ix_k \in I, the mean value theorem gives ξk\xi_k between xkx_k and x∗x^* with

xk+1−x∗=g(xk)−g(x∗)=g′(ξk) (xk−x∗),x_{k+1} - x^* = g(x_k) - g(x^*) = g'(\xi_k)\,(x_k - x^*),

hence ∣xk+1−x∗∣≤L∣xk−x∗∣≤Lδ\abs{x_{k+1} - x^*} \le L\abs{x_k - x^*} \le L\delta: xk+1∈Ix_{k+1} \in I and, by induction, ∣xk−x∗∣≤Lkδ→0\abs{x_k - x^*} \le L^k\delta \to 0. Since ξk→x∗\xi_k \to x^* and g′g' is continuous, ratio g′(ξk)g'(\xi_k) tends to g′(x∗)g'(x^*). For order pp, use the Taylor remainder of order pp instead of the mean value theorem: xk+1−x∗=g(p)(ηk) (xk−x∗)p/p!x_{k+1} - x^* = g^{(p)}(\eta_k)\,(x_k - x^*)^p/p! with ηk\eta_k between xkx_k and x∗x^*.

∎

The sign of g′(x∗)g'(x^*) determines convergence shape: with 0<g′(x∗)<10 < g'(x^*) < 1 error keeps its sign and iterates approach from one side; with −1<g′(x∗)<0-1 < g'(x^*) < 0 they switch sides each step. With ∣g′(x∗)∣>1\abs{g'(x^*)} > 1 the fixed point repels, however close the start. With g′(x∗)=0g'(x^*) = 0 (and g∈C2g \in C^2) convergence is at least quadratic.

InteractiveCobweb diagram
  • y=g(x)y = g(x)
  • y=xy = x
  • cobweb of iterates
  • slopes between −1-1 and 11
0.50
0.30
2.20
g(x)=1+s (x−1)+c (x−1)2g(x) = 1 + s\,(x - 1) + c\,(x - 1)^2
g′(x∗)g'(x^*)0.50
Last ratio (xk+1−x∗)/(xk−x∗)(x_{k+1} - x^*)/(x_k - x^*)0.5
Iterations until ∣ek∣<10−10|e_k| < 10^{-10}37
∣ek∣|e_k| after last iteration1.1·10⁻¹¹
0<g′(x∗)<10 < g'(x^*) < 1: linear monotone convergence; the cobweb is a staircase. Error is multiplied by ≈0.50\approx 0.50 each step.
g(x)=1+s (x−1)+c (x−1)2g(x) = 1 + s\,(x - 1) + c\,(x - 1)^2 has fixed point x∗=1x^* = 1 with g′(x∗)=sg'(x^*) = s. The cobweb alternates between curve y=g(x)y = g(x) and diagonal y=xy = x; the gray region contains lines through the fixed point with slopes between −1-1 and 11. Set ss to 0.50.5, −0.6-0.6, 00 and 1.151.15 and compare staircase, spiral, plummeting error and escape. Then with s=0.5s = 0.5, drag x0x_0 beyond x≈2.67x \approx 2.67: curvature creates a second, repelling fixed point, making convergence only local.

The right plot fingerprints each regime. With s=0.5s = 0.5 log-scale error is a straight line of slope log⁡100.5\log_{10} 0.5: one bit per iteration, like bisection. With s=0s = 0 the curve plunges because each step squares error. Kepler’s equation illustrates both sides: g(E)=M+esin⁡Eg(E) = M + e\sin E satisfies ∣g′(E)∣=e∣cos⁡E∣≤e\abs{g'(E)} = e\abs{\cos E} \le e, so it is contractive on the whole real line and iteration converges from any E0E_0 if e<1e < 1. But rate ecos⁡E∗e\cos E^* may be very close to 1.

[ ]Kepler by fixed point: rate is g'(E*)Browser
import math

def punto_fijo(g, x0, tol=1e-14, maxiter=5000):
    xs = [x0]
    for _ in range(maxiter):
        xs.append(g(xs[-1]))
        if abs(xs[-1] - xs[-2]) <= tol * max(1.0, abs(xs[-1])):
            break
    return xs

for M in (0.5, 0.01):
    for e in (0.3, 0.9, 0.99):
        xs = punto_fijo(lambda E: M + e * math.sin(E), M)
        Ex = xs[-1]
        errs = [abs(x - Ex) for x in xs[:-1]]
        k = len(errs) // 2                   # un cociente en mitad del recorrido
        print(f"M = {M}, e = {e}: {len(xs) - 1:4d} iteraciones   e_(k+1)/e_k = {errs[k + 1] / errs[k]:.4f}   "
              f"g'(E*) = e cos E* = {e * math.cos(Ex):.4f}   E* = {Ex:.4f}")

The measured ratio matches ecos⁡E∗e\cos E^* to four digits in all six cases. Rate depends on more than eccentricity: with M=0.5M = 0.5 and e=0.99e = 0.99, root E∗E^* is far from 0, cos⁡E∗\cos E^* is small and iteration fast; near perihelion (M=0.01M = 0.01), E∗E^* is small, cos⁡E∗≈1\cos E^* \approx 1, rate approaches ee and iteration count soars. Newton solves the same equation in a handful of steps in every case, but loses the global guarantee.

Measuring convergence order

In calculus you defined convergence order: xk→x∗x_k \to x^* has order p≥1p \ge 1 if ∣ek+1∣≤C∣ek∣p\abs{e_{k+1}} \le C\abs{e_k}^p for large kk, with ek=xk−x∗e_k = x_k - x^* (and C<1C < 1 if p=1p = 1). For a numerical method order is more than theoretical curiosity: it is the best check that an implementation is correct. If Newton’s error does not square at each step, code is wrong, usually the derivative.

Empirical order verification starts by taking logarithms in ∣ek+1∣≈C∣ek∣p\abs{e_{k+1}} \approx C\abs{e_k}^p:

log⁡∣ek+1∣≈plog⁡∣ek∣+log⁡C.\log\abs{e_{k+1}} \approx p\log\abs{e_k} + \log C.

Points (log⁡∣ek∣,log⁡∣ek+1∣)(\log\abs{e_k}, \log\abs{e_{k+1}}) lie on a line of slope pp. Three consecutive errors eliminate CC, giving estimator

pk=log⁡(∣ek+1∣/∣ek∣)log⁡(∣ek∣/∣ek−1∣).p_k = \frac{\log\left(\abs{e_{k+1}}/\abs{e_k}\right)}{\log\left(\abs{e_k}/\abs{e_{k-1}}\right)}.

Three precautions make it reliable:

  • Only in the asymptotic phase. Far from the root order has not settled, and pkp_k can be anything.
  • Never at the rounding floor. When ∣ek∣\abs{e_k} reaches 10−1510^{-15} or 10−1610^{-16}, error is noise and ratios meaningless. In practice use errors between 10−110^{-1} or 10−210^{-2} and 10−1310^{-13}.
  • If x∗x^* is unknown, replace ∣ek∣\abs{e_k} by steps dk=∣xk+1−xk∣d_k = \abs{x_{k+1} - x_k}. For a superlinear method, ek=(xk−xk+1)+ek+1e_k = (x_k - x_{k+1}) + e_{k+1} with ek+1=o(ek)e_{k+1} = o(e_k), so dk/∣ek∣→1d_k/\abs{e_k} \to 1 and steps inherit the order.

The same tool reappears with another variable: in numerical integration, differential-equation integrators and finite differences, error depends on step hh as ChpCh^p and order is the slope of log⁡(error)\log(\text{error}) versus log⁡h\log h. An order-4 integrator with measured slope 1 has a coefficient error.

[ ]Newton, secant and their measured ordersBrowser
import math

def newton(f, df, x0, maxiter=50):
    xs = [x0]
    for _ in range(maxiter):
        d = df(xs[-1])
        if d == 0:
            break
        x = xs[-1] - f(xs[-1]) / d
        xs.append(x)
        if x == xs[-2]:
            break
    return xs

def secante(f, x0, x1, maxiter=50):
    xs = [x0, x1]
    f0, f1 = f(x0), f(x1)
    for _ in range(maxiter):
        if f1 == f0:
            break
        x2 = x1 - f1 * (x1 - x0) / (f1 - f0)
        xs.append(x2)
        x0, f0, x1, f1 = x1, f1, x2, f(x2)
        if x1 == x0:
            break
    return xs

def orden_empirico(xs, raiz=None, ventana=(1e-13, 1e-2)):
    """Estimadores p_k con tres errores consecutivos dentro de la ventana."""
    if raiz is None:                         # sin raíz conocida: los pasos |x_{k+1} - x_k|
        e = [abs(b - a) for a, b in zip(xs, xs[1:])]
    else:
        e = [abs(x - raiz) for x in xs]
    lo, hi = ventana
    return [math.log(e[k + 1] / e[k]) / math.log(e[k] / e[k - 1])
            for k in range(1, len(e) - 1)
            if e[k - 1] < hi and e[k + 1] > lo and e[k] != e[k - 1]]

f = lambda x: math.cos(x) - x
df = lambda x: -math.sin(x) - 1
raiz, _ = biseccion(f, 0.0, 1.0)             # exacta hasta el último ulp
ventana = (1e-13, 1e-1)

xs_n = newton(f, df, 0.0)
xs_s = secante(f, 0.0, 1.0)
_, xs_b = biseccion(f, 0.0, 1.0)
for nombre, xs in [("Newton", xs_n), ("secante", xs_s)]:
    print(f"{nombre:8s} errores:", " ".join(f"{abs(x - raiz):.1e}" for x in xs[:10]))
    print(f"{'':8s} p_k con la raíz:   {[round(p, 3) for p in orden_empirico(xs, raiz, ventana)]}")
    print(f"{'':8s} p_k con los pasos: {[round(p, 3) for p in orden_empirico(xs, None, ventana)]}")
print("bisección p_k (sin sentido):", [round(p, 2) for p in orden_empirico(xs_b, raiz, ventana)][:6])
print("(1 + sqrt 5)/2 =", (1 + 5**0.5) / 2)

# un error típico: la derivada mal programada
df_mal = lambda x: -math.sin(x) - 0.5        # debía ser -sen x - 1
xs_m = newton(f, df_mal, 0.0)
print("\nNewton con la derivada mal: p_k =", [round(p, 3) for p in orden_empirico(xs_m, raiz, ventana)][:6])
e_m = [abs(x - raiz) for x in xs_m]
print("cocientes e_(k+1)/e_k:", [round(e_m[k + 1] / e_m[k], 3) for k in range(8, 12)],
      "  tasa predicha |1 - f'(x*)/df_mal(x*)| =", round(abs(1 - df(raiz) / df_mal(raiz)), 3))

Newton gives pk=2.0p_k = 2.0 and secant, with few noisy estimates, oscillates around 1.6181.618, the golden ratio derived below. Bisection gives meaningless numbers because its error does not decrease regularly (interval length decreases at exact rate 1/21/2). Step-based estimates closely resemble error-based ones, permitting order measurement without knowing the root. The last two lines explain this section: with an incorrectly coded derivative, Newton still converges, but at order 1 and the fixed-point theorem’s predicted rate. A test checking only the final result would miss it; measuring order catches it.

Newton-Raphson

The idea and its error

Newton–Raphson replaces ff by its tangent at xkx_k and takes the tangent’s axis crossing as the next approximation:

f(xk)+f′(xk)(x−xk)=0⟹xk+1=xk−f(xk)f′(xk).f(x_k) + f'(x_k)(x - x_k) = 0 \quad\Longrightarrow\quad x_{k+1} = x_k - \frac{f(x_k)}{f'(x_k)}.

Newton described it in De analysi (written 1669, published 1711) with equation x3−2x−5=0x^3 - 2x - 5 = 0, correcting a polynomial rather than iterating on xx; Raphson published the iterative form in 1690, still only for polynomials, and Thomas Simpson formulated it in 1740 for general equations with derivatives.

As a fixed point, g(x)=x−f(x)/f′(x)g(x) = x - f(x)/f'(x) satisfies g′(x)=f(x)f′′(x)/f′(x)2g'(x) = f(x)f''(x)/f'(x)^2, vanishing at a simple root. If f∈C3f \in C^3, then g∈C2g \in C^2 and the previous theorem guarantees order at least 2. But f∈C2f \in C^2 suffices, and the exact error equation is worth deriving because it contains the constant and explains the rest. With ek=xk−x∗e_k = x_k - x^*:

0=f(xk)−f′(xk) ek+12f′′(ξk) ek20 = f(x_k) - f'(x_k)\,e_k + \tfrac12 f''(\xi_k)\,e_k^2
Taylor expansion of ff about xkx_k evaluated at the root, where f(x∗)=0f(x^*) = 0 and x∗−xk=−ekx^* - x_k = -e_k, with Lagrange remainder: ξk\xi_k lies between xkx_k and x∗x^*.
1/4

The complete proof, choosing δ\delta so the error equation can be iterated, is the first guided exercise. In numbers: if ∣ek∣≈10−3\abs{e_k} \approx 10^{-3} and M≈1M \approx 1, then ∣ek+1∣≈10−6\abs{e_{k+1}} \approx 10^{-6} and ∣ek+2∣≈10−12\abs{e_{k+2}} \approx 10^{-12}. Correct digits double each step. Constant MM has geometric meaning: high curvature (large f′′f'') or a nearly horizontal tangent (small f′f') spoils linear approximation.

[ ]Newton's error constantBrowser
import math

f = lambda x: math.cos(x) - x
df = lambda x: -math.sin(x) - 1
d2f = lambda x: -math.cos(x)
raiz = biseccion(f, 0.0, 1.0)[0]

xs = newton(f, df, 1.0)
for k in range(len(xs) - 1):
    e, e1 = xs[k] - raiz, xs[k + 1] - raiz
    if e1 == 0:
        break
    print(f"k = {k}:  e_k = {e: .3e}   e_(k+1) / e_k^2 = {e1 / e**2: .5f}")
print(f"f''(x*) / (2 f'(x*)) = {d2f(raiz) / (2 * df(raiz)):.5f}")

Ratios ek+1/ek2e_{k+1}/e_k^2 settle at the predicted value once error is small, and the next iterate is already exact to machine precision.

Far from the root: divergence, cycles and basins

The theorem is local: it says nothing about the size of δ\delta. Far from the root Newton can do anything, and three classic pathologies occur with harmless-looking functions:

  • Divergence. For f(x)=arctan⁡xf(x) = \arctan x the step is xk+1=xk−(1+xk2)arctan⁡xkx_{k+1} = x_k - (1 + x_k^2)\arctan x_k. If ∣x0∣\abs{x_0} exceeds 1.39171.3917 (the solution of 2x=(1+x2)arctan⁡x2x = (1 + x^2)\arctan x), each tangent sends the iterate farther to the other side and ∣xk∣→∞\abs{x_k} \to \infty.
  • Cycles. With f(x)=x3−2x+2f(x) = x^3 - 2x + 2 and x0=0x_0 = 0 we obtain x1=0−2/(−2)=1x_1 = 0 - 2/(-2) = 1 and x2=1−1/1=0x_2 = 1 - 1/1 = 0: a 2-cycle. This is not an isolated accident: since g′(0)=f(0)f′′(0)/f′(0)2=0g'(0) = f(0)f''(0)/f'(0)^2 = 0, the cycle attracts a whole interval of starts.
  • Nearly zero derivative. If f′(xk)≈0f'(x_k) \approx 0, step f(xk)/f′(xk)f(x_k)/f'(x_k) is huge and the iterate shoots away. This happens for Kepler from E0=ME_0 = M when MM is small and ee near 1, because f′(E)=1−ecos⁡E≈1−ef'(E) = 1 - e\cos E \approx 1 - e.

The complex-plane picture is spectacular. Newton applies equally to complex polynomials, and coloring each starting point by the root it reaches reveals basins of attraction.

InteractiveNewton's fractal basins
  • root 1: 1.000
  • root 2: −0.500 + 0.866i
  • root 3: −0.500 − 0.866i
  • darker tone: more iterations
  • orbit of selected point
p(z)=z3−1p(z) = z^3 - 1
Selected z0z_0−0.2600 + 0.1500i
Destination (iterations)root 3 (33)
Neighbors one pixel away with another destination5 of 8
View magnification×1
Each pixel is a starting point z0z_0, colored by the root of pp reached by Newton (dimmer means more iterations). Click a point to see its orbit and how many of its 8 one-pixel neighbors reach another root; zoom ×4 there repeatedly. Far from the boundary everything is stable; at the boundary all basins coexist at every magnification. Try z3−2z+2z^3 - 2z + 2: patches in the text color never converge. Restricted to the real axis, z3−zz^3 - z is the one-variable Newton race.

The basin boundary is a fractal, the Julia set of rational map N(z)=z−p(z)/p′(z)N(z) = z - p(z)/p'(z), with a surprising property visible on zooming: every boundary point of one basin also belongs to the boundary of all others. This classical complex-dynamics theorem goes back to Fatou and Julia and is proved in Milnor’s Dynamics in One Complex Variable: for a rational map, the boundary of any attracting fixed point’s complete basin is the whole Julia set. Thus no boundary separates only two roots. Nearby, changing the starting point’s last digit changes the answer:

[ ]Three starting points a thousandth apartBrowser
import numpy as np

raices = np.roots([1, 0, 0, -1])                # z^3 - 1
def destino(z, maxiter=64):
    for k in range(1, maxiter + 1):
        z = z - (z**3 - 1) / (3 * z**2)
        d = np.abs(raices - z)
        if d.min() < 1e-6:
            return f"raíz {np.round(raices[d.argmin()], 4)} en {k} iteraciones"
    return "no converge"

z0 = -0.26 + 0.15j
for dz in (0, 1e-3, 1e-3j):
    print(f"z0 = {z0 + dz:.4f}: {destino(z0 + dz)}")

Three starting points separated by one thousandth reach three different roots, and the first needs 33 iterations: it is the point initially marked in the figure.

One useful common case gives Newton a global guarantee:

Proof

Suppose xk∈(x∗,b]x_k \in (x^*, b]. By convexity on [x∗,xk][x^*, x_k], the tangent at xkx_k lies below the graph also at x∗x^*: 0=f(x∗)≥f(xk)+f′(xk)(x∗−xk)0 = f(x^*) \ge f(x_k) + f'(x_k)(x^* - x_k). Rearranging gives f(xk)/f′(xk)≤xk−x∗f(x_k)/f'(x_k) \le x_k - x^*, that is xk+1≥x∗x_{k+1} \ge x^*. Also xk+1=xk−f(xk)/f′(xk)≤xkx_{k+1} = x_k - f(x_k)/f'(x_k) \le x_k because f(xk)≥0f(x_k) \ge 0 and f′(xk)>0f'(x_k) > 0. By induction all iterates lie in [x∗,b][x^*, b] and form a decreasing, lower-bounded sequence that converges; limit LL satisfies L=L−f(L)/f′(L)L = L - f(L)/f'(L), hence f(L)=0f(L) = 0 and L=x∗L = x^* since ff is strictly increasing.

∎

For Kepler with M∈[0,π]M \in [0, \pi], f(E)=E−esin⁡E−Mf(E) = E - e\sin E - M is increasing and convex on [0,π][0, \pi] (because f′′(E)=esin⁡E≥0f''(E) = e\sin E \ge 0) and f(π)=π−M≥0f(\pi) = \pi - M \ge 0. Thus Newton from E0=πE_0 = \pi always converges, without safeguards; for M∈[π,2π]M \in [\pi, 2\pi] the argument is symmetric, with concave ff and convergence from the left. The lab checks this.

Multiple roots

If x∗x^* is a root of multiplicity m≥2m \ge 2, f(x)=(x−x∗)mh(x)f(x) = (x - x^*)^m h(x) with h(x∗)≠0h(x^*) \ne 0, and Newton’s iteration function is

g(x)=x−(x−x∗) h(x)m h(x)+(x−x∗) h′(x),g′(x∗)=1−1m.g(x) = x - \frac{(x - x^*)\,h(x)}{m\,h(x) + (x - x^*)\,h'(x)}, \qquad g'(x^*) = 1 - \frac{1}{m}.

Convergence is linear at rate 1−1/m1 - 1/m: factor 1/21/2 per step for a double root, 2/32/3 for a triple root. Two classic fixes exist. If mm is known, modified Newton xk+1=xk−m f(xk)/f′(xk)x_{k+1} = x_k - m\,f(x_k)/f'(x_k) has g′(x∗)=0g'(x^*) = 0 and recovers order 2. Otherwise apply Newton to u=f/f′u = f/f', which has a simple root at x∗x^*: xk+1=xk−u(xk)/u′(xk)x_{k+1} = x_k - u(x_k)/u'(x_k) with u′=1−ff′′/f′2u' = 1 - f f''/f'^2, at the cost of needing f′′f''. Neither fixes conditioning: the multiple root still cannot be located better than εf1/m\varepsilon_f^{1/m}.

Secant, inverse quadratic interpolation and Brent

Secant and the golden ratio

If the derivative is unavailable or costs as much as ff, replace it with the quotient of the last two values. This is the secant method:

xk+1=xk−f(xk) xk−xk−1f(xk)−f(xk−1).x_{k+1} = x_k - f(x_k)\,\frac{x_k - x_{k-1}}{f(x_k) - f(x_{k-1})}.

An expansion analogous to Newton’s, using the interpolating polynomial instead of Taylor’s, gives ek+1≈C ek ek−1e_{k+1} \approx C\,e_k\,e_{k-1} with the same C=f′′(x∗)/(2f′(x∗))C = f''(x^*)/(2f'(x^*)). Assuming ∣ek+1∣≈A∣ek∣p\abs{e_{k+1}} \approx A\abs{e_k}^p gives ∣ek∣≈A∣ek−1∣p\abs{e_k} \approx A\abs{e_{k-1}}^p and, substituting,

A∣ek∣p≈C∣ek∣∣ek−1∣≈C∣ek∣(∣ek∣/A)1/p⟹p=1+1p⟹p=1+52≈1.618.A\abs{e_k}^p \approx C\abs{e_k}\abs{e_{k-1}} \approx C\abs{e_k}\left(\abs{e_k}/A\right)^{1/p} \quad\Longrightarrow\quad p = 1 + \frac1p \quad\Longrightarrow\quad p = \frac{1 + \sqrt5}{2} \approx 1.618.

Secant has lower order than Newton, but needs only one new evaluation per iteration. If evaluating f′f' costs the same as ff, two secant steps cost one Newton step and multiply digits by 1.6182≈2.618>21.618^2 \approx 2.618 > 2. Ostrowski formalized this comparison with efficiency index p1/wp^{1/w}, where ww is evaluations per iteration: 2≈1.414\sqrt2 \approx 1.414 for Newton and 1.6181.618 for secant.

Inverse quadratic interpolation (IQI) goes further: fit a parabola to the last three points as function x(y)x(y) rather than y(x)y(x), and evaluate it at y=0y = 0. No quadratic equation needs solving and there is always an answer. Its order is ≈1.839\approx 1.839, the real root of p3=p2+p+1p^3 = p^2 + p + 1.

Brent: secant speed with bisection’s guarantee

Secant and IQI share Newton’s problem: far from the root they can shoot away. Brent’s method (1973), refining Dekker (1969), combines them with bisection for the best of each. Together these form secant and Brent methods. The algorithm maintains three points:

  • bb, the best estimate (smallest ∣f∣\abs{f});
  • cc, such that f(b)f(b) and f(c)f(c) have opposite signs: [b,c][b, c] always contains a root;
  • aa, the previous estimate for interpolation.

At each step calculate an IQI candidate (or secant with only two distinct points) and accept it only inside the interval and when the step is less than half that from two iterations earlier. Otherwise bisect. The second condition is key: without it, tiny interpolation steps could advance arbitrarily slowly without shrinking the interval (Dekker’s defect). With it interpolation steps must decrease geometrically or yield to bisection, so the method cannot be catastrophically worse than bisection: Brent’s bound (1973, ch. 4) is at most order N2N^2 evaluations if bisection needs NN. Typically, for a simple root of a smooth function, once the interval is small all steps interpolate and convergence is superlinear.

InteractiveRoot-finder race
  • Bisection
  • Newton
  • Secant
  • Brent
f(x)=x3−2x−5f(x) = x^3 - 2x - 5
Bracket [a,b][a, b] for bisection, secant and Brent[2.00, 3.00]
2.50
Construction
Horizontal axis
0 evaluations
digitseval. 12corderBisection·401Newton0.7102.00Secant·81.80Brent·7mixed
Simple root and smooth function: Newton doubles the digits each step, and secant multiplies them by 1.6.
Four methods solve the same equation: bisection and Brent on [a,b][a, b], secant from aa and bb, Newton from movable x0x_0. Above, ff and the selected method's construction at the current step, with all four iterates below the axis. Below, correct digits versus ff evaluations: bisection is a straight line, Newton and secant curve upward faster. Compare functions: Newton escapes on arctan, cycles on the cycle example, and all crawl on the triple root, with Brent behind bisection. Switch the axis to iterations: who wins between Newton and secant now?

The race computes data live using the lesson cells’ algorithms; Brent translates the scipy.optimize.brentq variant line by line and reproduces its iteration count (checked in the lab, whose first cell also reproduces these figures). For x3−2x−5x^3 - 2x - 5 bisection needs 40 evaluations for 12 digits, Newton 10 (five iterations counting ff and f′f'), secant 8 and Brent 7. In iterations Newton wins: order 2 versus 1.618. Per evaluation, secant wins.

The triple root is humbling. Newton and secant drop to order 1. Brent repeatedly accepts interpolation steps satisfying its conditions but making little progress at a multiple root, forcing bisection every few steps: it needs 121 evaluations versus bisection’s 42. Indeed scipy.optimize.brentq with its default 100-iteration limit raises RuntimeError in (x−1)3(x - 1)^3 on [0,3][0, 3].

When to stop

A root finder needs a stopping criterion that neither triggers too soon (bad answer) nor fails to trigger (infinite loop). There are four ingredients; good code combines several:

  1. Interval length. If the method maintains a sign-changing interval, ∣b−c∣≤2 tol\abs{b - c} \le 2\,\mathrm{tol} certifies a root between bb and cc, within tol\mathrm{tol} of its midpoint and 2 tol2\,\mathrm{tol} of either endpoint. This gives a guarantee, so Brent uses it.
  2. Step size. For a superlinear method, ∣xk+1−xk∣\abs{x_{k+1} - x_k} excellently estimates ∣ek∣\abs{e_k} (as when measuring order with steps). For linear rate LL, error is ≈∣xk+1−xk∣/(1−L)\approx \abs{x_{k+1} - x_k}/(1 - L), potentially much larger than the step when LL is near 1.
  3. Residual. ∣f(xk)∣≤ftol\abs{f(x_k)} \le \mathrm{ftol} is meaningful only if you know the scale of ff and root conditioning: ∣ek∣≈∣f(xk)∣/∣f′(x∗)∣\abs{e_k} \approx \abs{f(x_k)}/\abs{f'(x^*)} for a simple root and ≈(m!∣f(xk)∣/∣f(m)(x∗)∣)1/m\approx (m!\abs{f(x_k)}/\abs{f^{(m)}(x^*)})^{1/m} for a multiple one.
  4. Maximum iteration count, always, so a pathological case ends with an explicit error instead of hanging.

Step or interval tolerance must combine absolute and relative parts: tol=xtol+rtol ∣x∣\mathrm{tol} = \mathrm{xtol} + \mathrm{rtol}\,\abs{x}. Relative alone fails for a zero root (criterion ∣Δx∣≤rtol∣x∣\abs{\Delta x} \le \mathrm{rtol}\abs{x} never holds when x→0x \to 0). Absolute alone fails for large roots: with x∗≈108x^* \approx 10^{8} the ulp is already 1.5×10−81.5\times 10^{-8} and xtol=10−12\mathrm{xtol} = 10^{-12} is unattainable. rtol\mathrm{rtol} cannot fall below a few machine epsilons: brentq therefore requires rtol≥4u\mathrm{rtol} \ge 4u and raises ValueError if asked for less. Defaults xtol=2e-12 and rtol=4*eps are precisely this combination.

Systems: Newton with a Jacobian

The method

For F:Rn→Rn\vb{F}: \R^n \to \R^n, the tangent becomes the linear approximation given by the Jacobian matrix J(x)=∂F/∂x\mat{J}(\vb{x}) = \partial\vb{F}/\partial\vb{x}, and Newton’s method for systems is

J(xk) sk=−F(xk),xk+1=xk+sk.\mat{J}(\vb{x}_k)\,\vb{s}_k = -\vb{F}(\vb{x}_k), \qquad \vb{x}_{k+1} = \vb{x}_k + \vb{s}_k.

Each iteration solves a linear system: solve it, never invert J\mat{J}. LU with partial pivoting costs 23n3\tfrac23 n^3 flops and is stable. For large sparse problems (PDE discretizations such as nonlinear finite elements) Krylov methods solve the system, giving inexact Newton.

Local theory is the same as in one variable. Suppose F\vb{F} is differentiable near root x∗\vb{x}^*, J\mat{J} is Lipschitz with constant γ\gamma (∥J(x)−J(y)∥≤γ∥x−y∥\norm{\mat{J}(\vb{x}) - \mat{J}(\vb{y})} \le \gamma\norm{\vb{x} - \vb{y}}), and J(x∗)\mat{J}(\vb{x}^*) is invertible. By formula F(xk)=F(xk)−F(x∗)=∫01J(x∗+tek) ek ⁣dt\vb{F}(\vb{x}_k) = \vb{F}(\vb{x}_k) - \vb{F}(\vb{x}^*) = \int_0^1 \mat{J}(\vb{x}^* + t\vb{e}_k)\,\vb{e}_k \dd t,

ek+1=ek−J(xk)−1F(xk)=J(xk)−1∫01(J(xk)−J(x∗+tek))ek ⁣dt,\vb{e}_{k+1} = \vb{e}_k - \mat{J}(\vb{x}_k)\inv\vb{F}(\vb{x}_k) = \mat{J}(\vb{x}_k)\inv \int_0^1 \big(\mat{J}(\vb{x}_k) - \mat{J}(\vb{x}^* + t\vb{e}_k)\big)\vb{e}_k \dd t,

and since ∥J(xk)−J(x∗+tek)∥≤γ(1−t)∥ek∥\norm{\mat{J}(\vb{x}_k) - \mat{J}(\vb{x}^* + t\vb{e}_k)} \le \gamma(1 - t)\norm{\vb{e}_k}, we obtain ∥ek+1∥≤γ2∥J(xk)−1∥∥ek∥2\norm{\vb{e}_{k+1}} \le \tfrac{\gamma}{2}\norm{\mat{J}(\vb{x}_k)\inv}\norm{\vb{e}_k}^2. Near x∗\vb{x}^*, ∥J(xk)−1∥≤2∥J(x∗)−1∥\norm{\mat{J}(\vb{x}_k)\inv} \le 2\norm{\mat{J}(\vb{x}^*)\inv} by continuity, and convergence is quadratic with constant γ∥J(x∗)−1∥\gamma\norm{\mat{J}(\vb{x}^*)\inv}: a nearly singular Jacobian at the solution spoils it, analogous to f′(x∗)≈0f'(x^*) \approx 0.

Finite-difference Jacobian. Without analytic J\mat{J}, approximate column jj by (F(x+hjej)−F(x))/hj(\vb{F}(\vb{x} + h_j\vb{e}_j) - \vb{F}(\vb{x}))/h_j, costing nn extra evaluations of F\vb{F} per iteration. Step choice matters: too large gives truncation error, too small cancellation. Standard choice hj=u max⁡(1,∣xj∣)h_j = \sqrt{u}\,\max(1, \abs{x_j}) with unit roundoff uu gives about 8 digits in J\mat{J}, enough for superlinear Newton convergence; why u\sqrt u is covered in optimal finite-difference step, lesson 13.

Far from the root a full step can worsen things. The standard solution measures progress with merit function ϕ(x)=12∥F(x)∥2\phi(\vb{x}) = \tfrac12\norm{\vb{F}(\vb{x})}^2 and shortens the step until it decreases. It works because Newton’s direction is always a descent direction for ϕ\phi:

∇ϕ(x)⊤s=F(x)⊤J(x) s=−F(x)⊤F(x)=−∥F(x)∥2<0.\grad\phi(\vb{x})\T\vb{s} = \vb{F}(\vb{x})\T\mat{J}(\vb{x})\,\vb{s} = -\vb{F}(\vb{x})\T\vb{F}(\vb{x}) = -\norm{\vb{F}(\vb{x})}^2 < 0.

Thus for small λ\lambda, ϕ(x+λs)<ϕ(x)\phi(\vb{x} + \lambda\vb{s}) < \phi(\vb{x}). Damped Newton with backtracking tries λ=1,12,14,…\lambda = 1, \tfrac12, \tfrac14, \dots and accepts the first satisfying Armijo condition ∥F(x+λs)∥≤(1−αλ)∥F(x)∥\norm{\vb{F}(\vb{x} + \lambda\vb{s})} \le (1 - \alpha\lambda)\norm{\vb{F}(\vb{x})}, with α=10−4\alpha = 10^{-4}, Kelley’s choice. Near the root λ=1\lambda = 1 is accepted and quadratic convergence returns. This is the same idea as damped Newton in optimization, with ϕ\phi instead of the objective.

InteractiveNewton, damped Newton and Broyden in the plane
  • x2+y2=4x^2 + y^2 = 4
  • y=1−exy = 1 - e^x
  • det⁡J=0\det\mat{J} = 0
  • Pure Newton
  • Damped Newton
  • Broyden
F(x,y)=[x2+y2−4ex+y−1]\vb{F}(x, y) = \begin{bmatrix} x^2 + y^2 - 4 \\ e^{x} + y - 1 \end{bmatrix}
Pure Newton, 0 F evalscomputing
Damped Newton, 0 F evalscomputing
Broyden, 0 F evalscomputing
det⁡J(x0)=0.011\det\mat{J}(\vb{x}_0) = 0.011,  ∥F(x0)∥=3.781\ \|\vb{F}(\vb{x}_0)\| = 3.781
The Jacobian is nearly singular at x0\vb{x}_0: the Newton step −J−1F-\mat{J}^{-1}\vb{F} is huge. Line search shortens it until ∥F∥\|\vb{F}\| actually decreases.
Final residual: pure ·, damped ·, Broyden ·
Zeros of F\vb{F} are intersections A and B of circle x2+y2=4x^2 + y^2 = 4 with curve y=1−exy = 1 - e^x. On the dashed curve det⁡J=0\det\mat{J} = 0. From the initial point near that curve, pure Newton takes a gigantic step and is lost; damped Newton shortens the step until ∥F∥\|\vb{F}\| falls and reaches B. Drag x0\vb{x}_0 (or click the plane) and find points where each method reaches a different root. Readouts count F\vb{F} evaluations, including line search.

Line search does not fix everything. It can get stuck at a local minimum of ∥F∥\norm{\vb{F}} that is not a root, where J\mat{J} is singular and ∇ϕ=J⊤F=0\grad\phi = \mat{J}\T\vb{F} = \vb{0} with F≠0\vb{F} \ne \vb{0}. Robust codes use trust regions: Powell’s hybrid method, implemented by MINPACK in hybrd and called by scipy.optimize.root(method='hybr'), blends Newton’s step with steepest descent of ϕ\phi (the dogleg step) inside a region whose radius adapts to progress.

Broyden: quasi-Newton for equations

Newton with a finite-difference Jacobian spends n+1n + 1 evaluations per iteration, dominating cost when nn is in the hundreds. Broyden’s idea (1965) generalizes secant: maintain approximation Bk≈J(xk)\mat{B}_k \approx \mat{J}(\vb{x}_k) and update it each step using already available information, without extra evaluations.

After step sk=xk+1−xk\vb{s}_k = \vb{x}_{k+1} - \vb{x}_k we observe change yk=F(xk+1)−F(xk)\vb{y}_k = \vb{F}(\vb{x}_{k+1}) - \vb{F}(\vb{x}_k). The true Jacobian satisfies yk≈Jsk\vb{y}_k \approx \mat{J}\vb{s}_k, motivating secant equation Bk+1sk=yk\mat{B}_{k+1}\vb{s}_k = \vb{y}_k. In one variable it determines Bk+1B_{k+1} and is exactly secant; in nn variables there are nn equations for n2n^2 unknowns. Broyden’s method chooses, among all matrices satisfying the secant equation, the nearest to Bk\mat{B}_k in Frobenius norm:

Bk+1=Bk+(yk−Bksk) sk⊤sk⊤sk.\mat{B}_{k+1} = \mat{B}_k + \frac{(\vb{y}_k - \mat{B}_k\vb{s}_k)\,\vb{s}_k\T}{\vb{s}_k\T\vb{s}_k}.

Closeness follows in one line: if B\mat{B} satisfies Bsk=yk\mat{B}\vb{s}_k = \vb{y}_k, then Bk+1−Bk=(B−Bk) sksk⊤/(sk⊤sk)\mat{B}_{k+1} - \mat{B}_k = (\mat{B} - \mat{B}_k)\,\vb{s}_k\vb{s}_k\T/(\vb{s}_k\T\vb{s}_k), and since sksk⊤/(sk⊤sk)\vb{s}_k\vb{s}_k\T/(\vb{s}_k\T\vb{s}_k) is an orthogonal projector of spectral norm 1, ∥Bk+1−Bk∥F≤∥B−Bk∥F\norm{\mat{B}_{k+1} - \mat{B}_k}_F \le \norm{\mat{B} - \mat{B}_k}_F. The rank-one correction leaves the action of Bk\mat{B}_k on directions orthogonal to sk\vb{s}_k untouched, since the step gave no information about them.

Nor must Bk\mat{B}_k be factored every step. By Sherman–Morrison its inverse Hk=Bk−1\mat{H}_k = \mat{B}_k\inv updates in O(n2)\bigO(n^2):

Hk+1=Hk+(sk−Hkyk) sk⊤Hksk⊤Hkyk.\mat{H}_{k+1} = \mat{H}_k + \frac{(\vb{s}_k - \mat{H}_k\vb{y}_k)\,\vb{s}_k\T\mat{H}_k}{\vb{s}_k\T\mat{H}_k\vb{y}_k}.

Speed is the price: Broyden converges locally superlinearly but not quadratically (Broyden, Dennis and Moré, 1973), because Bk\mat{B}_k need not converge to J(x∗)\mat{J}(\vb{x}^*); it is accurate only in directions that matter. It inherits Newton’s fragility far from a root, so production code globalizes it: MINPACK initially estimates the Jacobian by differences, updates it with Broyden’s formula, and recomputes only if progress stalls. The same philosophy applied to the Hessian with symmetry gives optimization’s BFGS methods.

Lab 1: serious root finders

Brent, line by line

Brent’s scipy.optimize.brentq variant fits in forty lines. This translation keeps its names: xcur is the best estimate, xblk the opposite endpoint of the sign-changing interval, and xpre the previous iterate; spre is the step two iterations earlier against which the candidate is compared.

[ ]brentq's Brent variant from scratchBrowser
import math
from scipy import optimize

def brent(f, a, b, xtol=2e-12, rtol=4 * 2.220446049250313e-16, maxiter=500):
    xpre, xcur = a, b
    fpre, fcur = f(xpre), f(xcur)
    nf, it = 2, 0
    if fpre == 0: return xpre, it, nf
    if fcur == 0: return xcur, it, nf
    if (fpre < 0) == (fcur < 0):
        raise ValueError("f(a) y f(b) deben tener signos opuestos")
    xblk = fblk = spre = scur = 0.0
    for it in range(1, maxiter + 1):
        if fpre != 0 and fcur != 0 and (fpre < 0) != (fcur < 0):
            xblk, fblk = xpre, fpre          # el cambio de signo está entre xcur y xpre
            spre = scur = xcur - xpre
        if abs(fblk) < abs(fcur):            # xcur debe ser el de menor |f|
            xpre, xcur, xblk = xcur, xblk, xcur
            fpre, fcur, fblk = fcur, fblk, fcur
        delta = (xtol + rtol * abs(xcur)) / 2
        sbis = (xblk - xcur) / 2
        if fcur == 0 or abs(sbis) < delta:   # el intervalo ya mide menos de 2*delta
            return xcur, it, nf
        if abs(spre) > delta and abs(fcur) < abs(fpre):
            if xpre == xblk:                 # secante
                stry = -fcur * (xcur - xpre) / (fcur - fpre)
            else:                            # interpolación cuadrática inversa
                dpre = (fpre - fcur) / (xpre - xcur)
                dblk = (fblk - fcur) / (xblk - xcur)
                stry = -fcur * (fblk * dblk - fpre * dpre) / (dblk * dpre * (fblk - fpre))
            if 2 * abs(stry) < min(abs(spre), 3 * abs(sbis) - delta):
                spre, scur = scur, stry      # paso de interpolación aceptado
            else:
                spre = scur = sbis           # rechazado: bisección
        else:
            spre = scur = sbis
        xpre, fpre = xcur, fcur
        xcur += scur if abs(scur) > delta else (delta if sbis > 0 else -delta)
        fcur = f(xcur)
        nf += 1
    raise RuntimeError(f"sin convergencia en {maxiter} iteraciones")

pruebas = {
    "x^3 - 2x - 5": (lambda x: x**3 - 2 * x - 5, 2.0, 3.0),
    "cos x - x": (lambda x: math.cos(x) - x, 0.0, 1.0),
    "Kepler e=0.9": (lambda E: E - 0.9 * math.sin(E) - 0.3, 0.0, math.pi),
    "x^3 - 2x + 2": (lambda x: x**3 - 2 * x + 2, -3.0, 2.0),
    "(x - 1)^3": (lambda x: (x - 1)**3, 0.0, 3.0),
}
print(f"{'función':14s} {'nuestro brent':>22s} {'scipy brentq':>22s}   bisección")
for nombre, (f, a, b) in pruebas.items():
    x, it, nf = brent(f, a, b)
    try:
        r = optimize.brentq(f, a, b, full_output=True)[1]
        ref = f"{r.iterations:3d} it, {r.function_calls:3d} eval."
    except RuntimeError as err:
        ref = "RuntimeError"
    _, xs = biseccion(f, a, b, xtol=2e-12)
    print(f"{nombre:14s} {it:8d} it, {nf:3d} eval.   {ref:>22s}   {len(xs) + 2:3d} eval.")

# la carrera de la figura: evaluaciones de f (f' cuenta como una) hasta 12 cifras correctas
def brent_iterados(f, a, b):
    xs = []
    def g(x):
        xs.append(x)
        return f(x)
    brent(g, a, b)
    return xs[2:]                            # quita f(a) y f(b)

def evals_12(xs, raiz, primera, por_iter):
    for i, x in enumerate(xs):
        if abs(x - raiz) / max(abs(raiz), 1) <= 1e-12:
            return primera + por_iter * i
    return None

print("\nevaluaciones hasta 12 cifras:  bisección  Newton  secante  Brent")
for nombre, (f, df, a, b, x0) in {
        "x^3 - 2x - 5": (lambda x: x**3 - 2 * x - 5, lambda x: 3 * x**2 - 2, 2.0, 3.0, 2.5),
        "(x - 1)^3": (lambda x: (x - 1)**3, lambda x: 3 * (x - 1)**2, 0.0, 3.0, 2.0)}.items():
    raiz = biseccion(f, a, b)[0]
    fila = [evals_12(biseccion(f, a, b)[1], raiz, 3, 1),
            evals_12(newton(f, df, x0, maxiter=60), raiz, 0, 2),
            evals_12(secante(f, a, b, maxiter=80), raiz, 1, 1),
            evals_12(brent_iterados(f, a, b), raiz, 3, 1)]
    print(f"{nombre:28s}" + "".join(f"{('no llega' if v is None else v):>9}" for v in fila))

Iterations and evaluations match SciPy exactly in the first four cases, confirming a faithful translation. For simple roots Brent needs 8 to 13 evaluations versus forty-something for bisection at the same tolerance. For the triple root it rises above one hundred and brentq exhausts its 100-iteration limit.

Kepler for a hundred thousand orbits at once

A satellite catalog or exoplanet simulation solves Kepler’s equation for millions of mean anomalies. In NumPy one iterates over the whole vector rather than looping over orbits, vectorizing the safeguard too. Each component keeps interval [M−e,M+e][M - e, M + e] containing the root because ∣E−M∣=e∣sin⁡E∣≤e\abs{E - M} = e\abs{\sin E} \le e; if its Newton step falls outside, it bisects.

[ ]Vectorized Kepler: pure versus safeguarded NewtonBrowser
import numpy as np

def kepler_newton(M, e, E0, tol=1e-12, maxiter=50):
    E = E0.copy()
    it = np.zeros(M.shape, int)
    activo = np.ones(M.shape, bool)
    for _ in range(maxiter):
        dE = (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
        E = np.where(activo, E - dE, E)
        it += activo
        activo &= ~(np.abs(dE) <= tol * np.maximum(1, np.abs(E)))
        if not activo.any():
            break
    return E, it

def kepler_seguro(M, e, tol=1e-12, maxiter=100):
    lo, hi = M - e, M + e                     # |E - M| = e |sen E| <= e
    E = M.copy()
    it = np.zeros(M.shape, int)
    nbis = np.zeros(M.shape, int)
    activo = np.ones(M.shape, bool)
    for _ in range(maxiter):
        f = E - e * np.sin(E) - M
        lo = np.where(f < 0, E, lo)           # el intervalo se estrecha con el signo de f
        hi = np.where(f > 0, E, hi)
        En = E - f / (1 - e * np.cos(E))
        fuera = (En < lo) | (En > hi)
        En = np.where(fuera, 0.5 * (lo + hi), En)
        paso = np.abs(En - E)
        E = np.where(activo, En, E)
        it += activo
        nbis += activo & fuera
        activo &= paso > tol * np.maximum(1, np.abs(E))
        if not activo.any():
            break
    return E, it, nbis

rng = np.random.default_rng(0)
M = rng.uniform(0, 2 * np.pi, 50_000)
for e in (0.9, 0.99):
    E1, it1 = kepler_newton(M, e, M)
    r1 = np.abs(E1 - e * np.sin(E1) - M)
    malos = np.sum(~(r1 < 1e-10))
    E2, it2, nb = kepler_seguro(M, e)
    r2 = np.abs(E2 - e * np.sin(E2) - M)
    E3, it3 = kepler_newton(M, e, np.full_like(M, np.pi))
    r3 = np.abs(E3 - e * np.sin(E3) - M)
    print(f"e = {e}")
    print(f"  Newton desde E0 = M:   {malos} de {M.size} sin converger, residuo máximo {np.nanmax(r1):.1e}", end="")
    if malos:
        d = np.minimum(M, 2 * np.pi - M)[~(r1 < 1e-10)]
        print(f", todas con M a menos de {d.max():.2f} de 0 o de 2 pi", end="")
    print()
    print(f"  salvaguardado:         residuo máximo {r2.max():.1e}, iteraciones media {it2.mean():.2f} "
          f"y máximo {it2.max()}, {np.mean(nb > 0):.1%} de las órbitas bisecan alguna vez")
    print(f"  Newton desde E0 = pi:  residuo máximo {r3.max():.1e}, iteraciones media {it3.mean():.2f} y máximo {it3.max()}")

With e=0.9e = 0.9 Newton from E0=ME_0 = M works for all orbits, but with e=0.99e = 0.99 fails on 795 of 50 000, with residuals up to 102010^{20}: all have MM within 0.440.44 of 00 or 2π2\pi, where f′(M)=1−ecos⁡Mf'(M) = 1 - e\cos M is small and the first step shoots away. Safeguarded Newton converges on all, averaging 5.9 iterations and at most 21; half need at least one bisection. Starting point E0=πE_0 = \pi, guaranteed by monotone convergence, also works on all without a safeguard, with slightly less work: 5.25 iterations on average and at most 12. When a specific problem permits such analysis, a good starting point can beat a generic safeguard.

Implied volatility with a black-box formula

For a root finder the pricing formula is an evaluable black box increasing in σ\sigma (its derivative, vega, is positive). Brent needs nothing else. Newton also needs vega and meets its greatest enemy: for deep out-of-the-money options at low volatility, vega is practically zero.

[ ]Implied volatility: Brent, Newton and an ill-conditioned rootBrowser
import math
from scipy import optimize
from scipy.special import ndtr

def precio_call(S, K, T, r, sigma):
    """Black-Scholes: para el buscador de raíces, una caja negra."""
    d1 = (math.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
    return S * ndtr(d1) - K * math.exp(-r * T) * ndtr(d1 - sigma * math.sqrt(T))

def vega(S, K, T, r, sigma):
    d1 = (math.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
    return S * math.sqrt(T) * math.exp(-0.5 * d1 * d1) / math.sqrt(2 * math.pi)

def newton_vol(g, S, K, T, r, s0, maxiter=50):
    s = s0
    for k in range(maxiter):
        v = vega(S, K, T, r, s)
        if v == 0:
            return f"vega = 0 en sigma = {s:.3g}"
        s_nuevo = s - g(s) / v
        if not (s_nuevo > 0 and math.isfinite(s_nuevo)):
            return f"sigma = {s_nuevo:.3g} tras {k + 1} pasos"
        if abs(s_nuevo - s) < 1e-14:
            return f"{s_nuevo:.6f} en {k + 1} pasos"
        s = s_nuevo
    return "sin convergencia"

casos = [("en el dinero", 100, 100, 1.0, 0.03, 0.25),
         ("muy fuera del dinero", 100, 150, 0.25, 0.03, 0.30)]
for nombre, S, K, T, r, sig in casos:
    C = precio_call(S, K, T, r, sig)
    g = lambda s: precio_call(S, K, T, r, s) - C
    x, res = optimize.brentq(g, 1e-4, 5.0, full_output=True)
    print(f"{nombre}: precio {C:.6f}  brentq -> {x:.12f} con {res.function_calls} evaluaciones")
    for s0 in (0.05, 0.2, 3.0):
        print(f"    Newton desde sigma0 = {s0}: {newton_vol(g, S, K, T, r, s0)}")

# muy dentro del dinero y a corto plazo: el precio casi no depende de sigma
S, K, T, r = 100, 60, 0.1, 0.0
for s in (0.05, 0.15, 0.25):
    print(f"\nsigma = {s}: precio = {precio_call(S, K, T, r, s):.15f}   vega = {vega(S, K, T, r, s):.2e}", end="")
print()

At the money Brent needs 7 evaluations and Newton converges from 0.05 and 0.2, but from σ0=3\sigma_0 = 3 its first step sends σ\sigma to −2.92-2.92. Deep out of the money, Newton from σ0=0.05\sigma_0 = 0.05 meets tiny vega, jumps to σ≈1052\sigma \approx 10^{52}, where vega is exactly zero. Brent, which does not use vega, converges in both cases (20 evaluations in the second).

The final case concerns conditioning. Deep in the money and near expiry, the call price equals intrinsic value S−K=40S - K = 40 to the last digit printed for σ=0.05\sigma = 0.05 and σ=0.15\sigma = 0.15, with vegas 10−22610^{-226} and 6×10−256\times 10^{-25}; with σ=0.25\sigma = 0.25 price changes only in the eleventh decimal place. Condition number 1/vega1/\text{vega} is astronomical: implied volatility effectively does not exist; any solver returns some number satisfying ∣f∣≈0\abs{f} \approx 0 without meaning. The practical answer is to calculate implied volatility from the out-of-the-money option (here the put at the same strike), whose price does depend on σ\sigma.

Lab 2: Newton and Broyden for systems

The test problem is Bratu’s equation, −u′′=λeu-u'' = \lambda e^{u} on (0,1)(0, 1) with u(0)=u(1)=0u(0) = u(1) = 0, a classical combustion model: generated heat grows exponentially with temperature and dissipates by conduction; the stationary solution balances both. With centered differences at nn interior points, h=1/(n+1)h = 1/(n + 1), equilibrium is the nonlinear system

Fi(u)=−ui−1+2ui−ui+1h2−λeui=0,i=1,…,n,F_i(\vb{u}) = \frac{-u_{i-1} + 2u_i - u_{i+1}}{h^2} - \lambda e^{u_i} = 0, \qquad i = 1, \dots, n,

with tridiagonal Jacobian J=A−λdiag⁡(eu)\mat{J} = \mat{A} - \lambda\diag(e^{\vb{u}}). For λ\lambda below critical value λ∗≈3.51\lambda^* \approx 3.51 there are two solutions; Newton from u=0\vb{u} = \vb{0} finds the lower-temperature one.

[ ]Newton with finite-difference Jacobian, LU and damping; BroydenBrowser
import numpy as np
from scipy.linalg import lu_factor, lu_solve
from scipy import optimize

class Contador:
    """Envuelve F para contar sus evaluaciones."""
    def __init__(self, F):
        self.F, self.n = F, 0
    def __call__(self, x):
        self.n += 1
        return self.F(x)

def jacobiano_dif(F, x, Fx):
    J = np.empty((Fx.size, x.size))
    for j in range(x.size):
        h = np.sqrt(np.finfo(float).eps) * max(1.0, abs(x[j]))
        xh = x.copy()
        xh[j] += h
        J[:, j] = (F(xh) - Fx) / h
    return J

def newton_sistema(F, x0, J=None, tol=1e-10, maxiter=50, amortiguar=True, alfa=1e-4):
    x = np.array(x0, dtype=float)
    Fx = F(x)
    hist = [np.linalg.norm(Fx)]
    for _ in range(maxiter):
        if hist[-1] <= tol:
            break
        Jx = J(x) if J is not None else jacobiano_dif(F, x, Fx)
        s = lu_solve(lu_factor(Jx), -Fx)          # resolver, nunca invertir
        lam = 1.0
        while True:
            xn = x + lam * s
            Fn = F(xn)
            if not amortiguar or np.linalg.norm(Fn) <= (1 - alfa * lam) * hist[-1] or lam < 1e-10:
                break
            lam /= 2                              # Armijo hacia atrás
        x, Fx = xn, Fn
        hist.append(np.linalg.norm(Fx))
    return x, hist

def broyden(F, x0, B0, tol=1e-10, maxiter=100):
    x = np.array(x0, dtype=float)
    Fx = F(x)
    H = np.linalg.inv(B0)                         # una sola inversa, al principio
    hist = [np.linalg.norm(Fx)]
    for _ in range(maxiter):
        if hist[-1] <= tol:
            break
        s = -H @ Fx
        xn = x + s
        Fn = F(xn)
        y = Fn - Fx
        Hy = H @ y
        H += np.outer(s - Hy, s @ H) / (s @ Hy)   # Sherman-Morrison: O(n^2)
        x, Fx = xn, Fn
        hist.append(np.linalg.norm(Fx))
    return x, hist

def bratu(n, lam):
    h = 1 / (n + 1)
    def F(u):
        up = np.concatenate([[0.0], u, [0.0]])
        return (-up[:-2] + 2 * up[1:-1] - up[2:]) / h**2 - lam * np.exp(u)
    def J(u):
        return (np.diag(np.full(n, 2 / h**2)) - np.diag(np.full(n - 1, 1 / h**2), 1)
                - np.diag(np.full(n - 1, 1 / h**2), -1) - lam * np.diag(np.exp(u)))
    return F, J

n = 40
for lam in (1.0, 3.0, 3.5):
    F, J = bratu(n, lam)
    u0 = np.zeros(n)
    print(f"lambda = {lam}")
    Fc = Contador(F); u, h = newton_sistema(Fc, u0, J=J)
    print(f"  Newton, J analítico:      {len(h) - 1:2d} it, {Fc.n:4d} eval. de F   max u = {u.max():.6f}   "
          f"|F|: {' '.join(f'{v:.0e}' for v in h)}")
    Fc = Contador(F); u, h = newton_sistema(Fc, u0)
    print(f"  Newton, J por diferencias: {len(h) - 1:2d} it, {Fc.n:4d} eval. de F   max u = {u.max():.6f}")
    Fc = Contador(F); B0 = jacobiano_dif(Fc, u0, Fc(u0)); u, h = broyden(Fc, u0, B0)
    print(f"  Broyden, B0 por difer.:    {len(h) - 1:2d} it, {Fc.n:4d} eval. de F   max u = {u.max():.6f}")
    Fc = Contador(F); sol = optimize.root(Fc, u0, method="hybr")
    print(f"  scipy root (hybr):                {Fc.n:4d} eval. de F   max u = {sol.x.max():.6f}   éxito: {sol.success}")

All four variants reach the same solution; cost differs. With analytic Jacobian Newton needs 3 to 7 iterations and shows the quadratic signature: residual passes 10−210^{-2}, 10−610^{-6} and 10−1310^{-13}, its exponent nearly doubling each step. Finite differences take the same iterations but n+1=41n + 1 = 41 evaluations each. Broyden pays nn initial Jacobian evaluations once, then one per iteration: 4 to 10 iterations, more than Newton, but 46 to 52 evaluations versus 124 to 288 for finite-difference Newton. root with hybr behaves like trust-region Broyden, as MINPACK should: 51 to 59 evaluations, nn initial Jacobian evaluations plus 11 to 19. Notice λ=3.5\lambda = 3.5 near criticality: Newton needs more iterations because at turning point λ∗\lambda^* the solution Jacobian becomes singular, and nearby the quadratic convergence constant proportional to ∥J(x∗)−1∥\norm{\mat{J}(\vb{x}^*)\inv} grows.

The earlier planar system shows the other side: robustness.

[ ]Far from the root: pure, damped and BroydenBrowser
import numpy as np
import warnings

F2 = lambda v: np.array([v[0]**2 + v[1]**2 - 4, np.exp(v[0]) + v[1] - 1])
J2 = lambda v: np.array([[2 * v[0], 2 * v[1]], [np.exp(v[0]), 1.0]])

for x0 in [(1.0, 1.0), (0.5, 0.3), (-0.4, -0.5)]:
    x0 = np.array(x0)
    print(f"x0 = {x0},  det J(x0) = {np.linalg.det(J2(x0)):.3f}")
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        for nombre, (x, h) in [("puro", newton_sistema(F2, x0, J=J2, amortiguar=False)),
                               ("amortiguado", newton_sistema(F2, x0, J=J2)),
                               ("Broyden", broyden(F2, x0, J2(x0), maxiter=40))]:
            print(f"   {nombre:12s} {len(h) - 1:2d} it   x = {np.round(x, 4)}   |F| = {h[-1]:.1e}")

From (0.5,0.3)(0.5, 0.3), where det⁡J≈0.01\det\mat{J} \approx 0.01, pure Newton takes a huge first step and never recovers; damped Newton reaches root (1.0042,−1.7296)(1.0042, -1.7296) in a few iterations; Broyden without line search inherits Newton’s fragility and ends at nan. This is why production code does not use bare methods.

The professional version

SciPy functionMethodRequiresWhen
optimize.brentq(f, a, b)Brent (lesson variant)sign-changing intervaldefault in one variable
optimize.bisect(f, a, b)bisectionintervalif ff is noisy or discontinuous
optimize.newton(f, x0, fprime=df)Newtonf′f' and good x0x_0cheap derivative and reliable start
optimize.newton(f, x0)secantgood x0x_0no derivative or bracket
optimize.newton(f, x0, fprime, fprime2)Halley (order 3)f′f' and f′′f''very cheap derivatives
optimize.root_scalar(f, method=...)all abovemethod-dependentunified interface
optimize.root(F, x0, method="hybr")Powell hybrid (MINPACK)only F\vb{F}small and medium systems
optimize.root(F, x0, method="krylov")inexact Newton–Krylovonly F\vb{F}large systems

optimize.newton also accepts a vector of starting points and iterates all components at once, like vectorized Kepler (without safeguarding). In PyTorch and JAX, when a root finder is part of a trained model, rather than backpropagating through iterations use the implicit function theorem,  ⁣dx∗/ ⁣dθ=−fx−1fθ\dd x^*/\dd\theta = -f_x\inv f_\theta, covered in lesson 16 on differentiating iterative solvers.

[ ]SciPy for scalar equations and systemsBrowser
import math
import numpy as np
from scipy import optimize

f = lambda x: x**3 - 2 * x - 5
df = lambda x: 3 * x**2 - 2
d2f = lambda x: 6 * x

for metodo, kw in [("brentq", dict(bracket=[2, 3])), ("bisect", dict(bracket=[2, 3])),
                   ("newton", dict(x0=2.5, fprime=df)), ("secant", dict(x0=2.0, x1=3.0)),
                   ("halley", dict(x0=2.5, fprime=df, fprime2=d2f))]:
    r = optimize.root_scalar(f, method=metodo, **kw)
    print(f"{metodo:7s} x = {r.root:.15f}  iteraciones {r.iterations:2d}  evaluaciones {r.function_calls:2d}")

# Kepler vectorizado con optimize.newton (sin salvaguarda)
M = np.linspace(0.1, 6.0, 5)
E = optimize.newton(lambda E: E - 0.5 * np.sin(E) - M, M, fprime=lambda E: 1 - 0.5 * np.cos(E))
print("\nKepler e = 0.5:", np.round(E, 6), " residuo máximo:", np.abs(E - 0.5 * np.sin(E) - M).max())

Common mistakes

Exercises

NumericHow many bisections?
You apply bisection to a continuous function changing sign on [0,1][0, 1]. What is the minimum number of iterations (midpoint evaluations) guaranteeing a sign-changing interval shorter than 10−1010^{-10}?
NumericThree Newton steps
Apply three Newton iterations to f(x)=x2−2f(x) = x^2 - 2 from x0=1x_0 = 1. What is x3x_3? Give the exact fraction or seven decimal places.
NumericThe error constant
Newton's method on f(x)=x3−2x−5f(x) = x^3 - 2x - 5, with root x∗≈2.0945515x^* \approx 2.0945515, has error ek+1/ek2→Ce_{k+1}/e_k^2 \to C. What is CC?
QuizFour rewritings
Equation x3−2x−5=0x^3 - 2x - 5 = 0 has real root x∗≈2.0946x^* \approx 2.0946. For which rewritings x=g(x)x = g(x) does xk+1=g(xk)x_{k+1} = g(x_k) converge when x0x_0 is sufficiently close to x∗x^*?

More than one answer may be correct.

NumericMeasuring an order
Secant on Kepler's equation E−0.9sin⁡E−0.3=0E - 0.9\sin E - 0.3 = 0 from x0=0x_0 = 0 and x1=πx_1 = \pi gives errors ∣e8∣=7.86×10−4\abs{e_{8}} = 7.86\times 10^{-4}, ∣e9∣=7.46×10−6\abs{e_9} = 7.46\times 10^{-6} and ∣e10∣=3.97×10−9\abs{e_{10}} = 3.97\times 10^{-9} at x8x_8, x9x_9 and x10x_{10}. Estimate order from these errors.
QuizNewton at a triple root
You apply Newton to f(x)=(x−1)3exf(x) = (x - 1)^3 e^{x} from x0=1.5x_0 = 1.5. What happens and what restores quadratic convergence?
QuizA misleading residual
A program seeks a root of a degree-7 polynomial which, unknown to it, is expanded (x−1)7(x - 1)^7. It stops at x=1.03x = 1.03 because ∣f(1.03)∣≤10−10\abs{f(1.03)} \le 10^{-10}. What is true?
QuizBroyden in one dimension
What does Broyden's method reduce to for a single equation f(x)=0f(x) = 0?
ProofNewton's quadratic convergence
Prove: Let f∈C2f \in C^2 near x∗x^* with f(x∗)=0f(x^*) = 0 and f′(x∗)≠0f'(x^*) \ne 0. There exists δ>0\delta > 0 such that if ∣x0−x∗∣≤δ\abs{x_0 - x^*} \le \delta, Newton iterates are defined, remain within ≤δ\le \delta of x∗x^* and satisfy ∣xk+1−x∗∣≤M∣xk−x∗∣2\abs{x_{k+1} - x^*} \le M\abs{x_k - x^*}^2, with ek+1/ek2→f′′(x∗)/(2f′(x∗))e_{k+1}/e_k^2 \to f''(x^*)/(2f'(x^*)).
0
Write ek=xk−x∗e_k = x_k - x^* and Iδ=[x∗−δ,x∗+δ]I_\delta = [x^* - \delta, x^* + \delta].

Step 1 of 4. First ensure the step is defined. How do you choose an initial δ0\delta_0?

CodeSafeguarded Newton
Implement safeguarded_newton(f, df, a, b, tol=1e-12, maxiter=200) returning a root of f in [a, b] given opposite signs for f(a) and f(b) (raise ValueError otherwise). Start at the midpoint, always maintain a sign-changing bracket, take a Newton step when it lies within the bracket and reduces step size sufficiently, and bisect otherwise. Never evaluate f outside [a, b] or divide by df(x) = 0. Stop when the Newton or bisection step is smaller than tol.
import math

def safeguarded_newton(f, df, a, b, tol=1e-12, maxiter=200):
  """Newton con salvaguarda de bisección. Devuelve una raíz de f en [a, b]."""
  fa, fb = f(a), f(b)
  # tu código: comprueba el cambio de signo; orienta el intervalo; itera Newton desde el
  # punto medio y biseca si el paso sale del intervalo o no se reduce lo bastante;
  # actualiza el intervalo con el signo de f en cada nuevo iterado
  return (a + b) / 2
Shift+Enter to run

Summary

Key idea
A root finder is judged by its guarantees, convergence speed and stopping rule. Bisection guarantees and Newton is fast; production methods like Brent or Newton with line search combine both, and root conditioning 1/∣f′(x∗)∣1/|f'(x^*)| determines meaningful precision.
  • Bisection: with a sign change, always converges one bit per evaluation; ⌈log⁡2((b−a)/τ)⌉\lceil\log_2((b - a)/\tau)\rceil iterations for interval length τ\tau. In floating point use midpoint a+(b−a)/2a + (b - a)/2, compare signs and stop when no doubles remain inside.
  • Fixed point: converges locally if ∣g′(x∗)∣<1\abs{g'(x^*)} < 1 at rate g′(x∗)g'(x^*); order is that of the first nonzero derivative of gg at x∗x^*.
  • Empirical order: pk=log⁡(ek+1/ek)/log⁡(ek/ek−1)p_k = \log(e_{k+1}/e_k)/\log(e_k/e_{k-1}) in the asymptotic phase above noise, or use steps if the root is unknown. This tests an implementation.
  • Newton: quadratic near a simple root, with ek+1/ek2→f′′/(2f′)e_{k+1}/e_k^2 \to f''/(2f'); linear at rate 1−1/m1 - 1/m for multiplicity mm; far away it can diverge, cycle or jump among fractal basins.
  • Secant and Brent: secant has order 1.6181.618 with one evaluation per step; Brent combines secant, inverse quadratic interpolation and bisection with a bracket guarantee.
  • Systems: Newton solves Js=−F\mat{J}\vb{s} = -\vb{F} with LU, is quadratic with invertible J(x∗)\mat{J}(\vb{x}^*), and is globalized by line search on ∥F∥\norm{\vb{F}} or trust regions. Broyden updates the Jacobian with rank one and converges superlinearly with one evaluation per iteration.
  • Stopping: interval or step with xtol+rtol∣x∣\mathrm{xtol} + \mathrm{rtol}\abs{x}, residual only scaled by conditioning, and always a maximum iteration count.