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 for each volatility . Implied volatility solves , 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 and source obeys Shockley’s equation . 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 at time comes from eccentric anomaly , satisfying with 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 : the unknown appears on both sides. Each step requires solving a system 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 .
Bisection: a guarantee
If is continuous on and and have opposite signs, the intermediate value theorem guarantees at least one root inside. Bisection uses that guarantee without further assumptions: evaluate at midpoint , 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 : iteration count is the same for as for a fiendish function. This is both strength and limit. Each evaluation gains exactly one bit, decimal digits. In convergence-order terminology, bisection converges R-linearly at rate : 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:
- Compute the midpoint as . Formula overflows if and are large and same-signed (near their sum is already infinite), while does not, and never leaves .
- Compare signs rather than multiplying. can give through underflow when both values are small, silently defeating test .
- Stop when equals an endpoint. No floating-point number remains between and and continuing changes nothing. Without tolerance this happens after about fifty iterations on an interval like : its length reaches one ulp.
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 , namely . With xtol = 1e-6 the count matches the formula. Multiplying two values of size gives , 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 the computer evaluates with (rounding error evaluating , or simulation noise). If is a simple root, , so vanishes near with
The number is the absolute condition number of the problem “root of ”, as in lesson 3: how far the answer moves per unit perturbation of the data, here the function itself. A root where crosses the axis almost horizontally is ill-conditioned.
If the root has multiplicity , meaning , the first surviving Taylor term is and
The -th root is devastating: perturbation moves a seventh-order root by order . This is not an algorithm defect. The problem itself contains no more information on the root’s location.
The figure computes this live; the cell repeats it with NumPy using the same IEEE doubles:
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 Horner noise near is about , and the computed sign is wrong up to from the root, of the order predicted by ; other multiplicities agree similarly. The second reading matters for code: with , condition holds throughout . A tiny residual says nothing about distance to an ill-conditioned root. We revisit this under stopping criteria.
Fixed-point iteration
Every equation can be rewritten as in many ways, allowing fixed-point iteration . Kepler’s equation is already written this way, , and Newton is also a fixed-point iteration, with . This theory explains the speed of almost every method in the lesson.
The Banach fixed-point theorem gives global convergence when is contractive on a closed interval mapped into itself. In practice that is rare, but a local result holds:
Proof
By continuity of there are and with on . If , the mean value theorem gives between and with
hence : and, by induction, . Since and is continuous, ratio tends to . For order , use the Taylor remainder of order instead of the mean value theorem: with between and .
∎The sign of determines convergence shape: with error keeps its sign and iterates approach from one side; with they switch sides each step. With the fixed point repels, however close the start. With (and ) convergence is at least quadratic.
The right plot fingerprints each regime. With log-scale error is a straight line of slope : one bit per iteration, like bisection. With the curve plunges because each step squares error. Kepler’s equation illustrates both sides: satisfies , so it is contractive on the whole real line and iteration converges from any if . But rate may be very close to 1.
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 to four digits in all six cases. Rate depends on more than eccentricity: with and , root is far from 0, is small and iteration fast; near perihelion (), is small, , rate approaches 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: has order if for large , with (and if ). 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 :
Points lie on a line of slope . Three consecutive errors eliminate , giving estimator
Three precautions make it reliable:
- Only in the asymptotic phase. Far from the root order has not settled, and can be anything.
- Never at the rounding floor. When reaches or , error is noise and ratios meaningless. In practice use errors between or and .
- If is unknown, replace by steps . For a superlinear method, with , so 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 as and order is the slope of versus . An order-4 integrator with measured slope 1 has a coefficient error.
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 and secant, with few noisy estimates, oscillates around , the golden ratio derived below. Bisection gives meaningless numbers because its error does not decrease regularly (interval length decreases at exact rate ). 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 by its tangent at and takes the tangent’s axis crossing as the next approximation:
Newton described it in De analysi (written 1669, published 1711) with equation , correcting a polynomial rather than iterating on ; 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, satisfies , vanishing at a simple root. If , then and the previous theorem guarantees order at least 2. But suffices, and the exact error equation is worth deriving because it contains the constant and explains the rest. With :
The complete proof, choosing so the error equation can be iterated, is the first guided exercise. In numbers: if and , then and . Correct digits double each step. Constant has geometric meaning: high curvature (large ) or a nearly horizontal tangent (small ) spoils linear approximation.
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 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 . Far from the root Newton can do anything, and three classic pathologies occur with harmless-looking functions:
- Divergence. For the step is . If exceeds (the solution of ), each tangent sends the iterate farther to the other side and .
- Cycles. With and we obtain and : a 2-cycle. This is not an isolated accident: since , the cycle attracts a whole interval of starts.
- Nearly zero derivative. If , step is huge and the iterate shoots away. This happens for Kepler from when is small and near 1, because .
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.
The basin boundary is a fractal, the Julia set of rational map , 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:
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 . By convexity on , the tangent at lies below the graph also at : . Rearranging gives , that is . Also because and . By induction all iterates lie in and form a decreasing, lower-bounded sequence that converges; limit satisfies , hence and since is strictly increasing.
∎For Kepler with , is increasing and convex on (because ) and . Thus Newton from always converges, without safeguards; for the argument is symmetric, with concave and convergence from the left. The lab checks this.
Multiple roots
If is a root of multiplicity , with , and Newton’s iteration function is
Convergence is linear at rate : factor per step for a double root, for a triple root. Two classic fixes exist. If is known, modified Newton has and recovers order 2. Otherwise apply Newton to , which has a simple root at : with , at the cost of needing . Neither fixes conditioning: the multiple root still cannot be located better than .
Secant, inverse quadratic interpolation and Brent
Secant and the golden ratio
If the derivative is unavailable or costs as much as , replace it with the quotient of the last two values. This is the secant method:
An expansion analogous to Newton’s, using the interpolating polynomial instead of Taylor’s, gives with the same . Assuming gives and, substituting,
Secant has lower order than Newton, but needs only one new evaluation per iteration. If evaluating costs the same as , two secant steps cost one Newton step and multiply digits by . Ostrowski formalized this comparison with efficiency index , where is evaluations per iteration: for Newton and for secant.
Inverse quadratic interpolation (IQI) goes further: fit a parabola to the last three points as function rather than , and evaluate it at . No quadratic equation needs solving and there is always an answer. Its order is , the real root of .
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:
- , the best estimate (smallest );
- , such that and have opposite signs: always contains a root;
- , 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 evaluations if bisection needs . Typically, for a simple root of a smooth function, once the interval is small all steps interpolate and convergence is superlinear.
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 bisection needs 40 evaluations for 12 digits, Newton 10 (five iterations counting and ), 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 on .
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:
- Interval length. If the method maintains a sign-changing interval, certifies a root between and , within of its midpoint and of either endpoint. This gives a guarantee, so Brent uses it.
- Step size. For a superlinear method, excellently estimates (as when measuring order with steps). For linear rate , error is , potentially much larger than the step when is near 1.
- Residual. is meaningful only if you know the scale of and root conditioning: for a simple root and for a multiple one.
- 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: . Relative alone fails for a zero root (criterion never holds when ). Absolute alone fails for large roots: with the ulp is already and is unattainable. cannot fall below a few machine epsilons: brentq therefore requires 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 , the tangent becomes the linear approximation given by the Jacobian matrix , and Newton’s method for systems is
Each iteration solves a linear system: solve it, never invert . LU with partial pivoting costs 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 is differentiable near root , is Lipschitz with constant (), and is invertible. By formula ,
and since , we obtain . Near , by continuity, and convergence is quadratic with constant : a nearly singular Jacobian at the solution spoils it, analogous to .
Finite-difference Jacobian. Without analytic , approximate column by , costing extra evaluations of per iteration. Step choice matters: too large gives truncation error, too small cancellation. Standard choice with unit roundoff gives about 8 digits in , enough for superlinear Newton convergence; why is covered in optimal finite-difference step, lesson 13.
Damping and line search
Far from the root a full step can worsen things. The standard solution measures progress with merit function and shortens the step until it decreases. It works because Newton’s direction is always a descent direction for :
Thus for small , . Damped Newton with backtracking tries and accepts the first satisfying Armijo condition , with , Kelley’s choice. Near the root is accepted and quadratic convergence returns. This is the same idea as damped Newton in optimization, with instead of the objective.
Line search does not fix everything. It can get stuck at a local minimum of that is not a root, where is singular and with . 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 (the dogleg step) inside a region whose radius adapts to progress.
Broyden: quasi-Newton for equations
Newton with a finite-difference Jacobian spends evaluations per iteration, dominating cost when is in the hundreds. Broyden’s idea (1965) generalizes secant: maintain approximation and update it each step using already available information, without extra evaluations.
After step we observe change . The true Jacobian satisfies , motivating secant equation . In one variable it determines and is exactly secant; in variables there are equations for unknowns. Broyden’s method chooses, among all matrices satisfying the secant equation, the nearest to in Frobenius norm:
Closeness follows in one line: if satisfies , then , and since is an orthogonal projector of spectral norm 1, . The rank-one correction leaves the action of on directions orthogonal to untouched, since the step gave no information about them.
Nor must be factored every step. By Sherman–Morrison its inverse updates in :
Speed is the price: Broyden converges locally superlinearly but not quadratically (Broyden, Dennis and Moré, 1973), because need not converge to ; 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.
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 containing the root because ; if its Newton step falls outside, it bisects.
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 Newton from works for all orbits, but with fails on 795 of 50 000, with residuals up to : all have within of or , where 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 , 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 (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.
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 its first step sends to . Deep out of the money, Newton from meets tiny vega, jumps to , 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 to the last digit printed for and , with vegas and ; with price changes only in the eleventh decimal place. Condition number is astronomical: implied volatility effectively does not exist; any solver returns some number satisfying 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 .
Lab 2: Newton and Broyden for systems
The test problem is Bratu’s equation, on with , a classical combustion model: generated heat grows exponentially with temperature and dissipates by conduction; the stationary solution balances both. With centered differences at interior points, , equilibrium is the nonlinear system
with tridiagonal Jacobian . For below critical value there are two solutions; Newton from finds the lower-temperature one.
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 , and , its exponent nearly doubling each step. Finite differences take the same iterations but evaluations each. Broyden pays 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, initial Jacobian evaluations plus 11 to 19. Notice near criticality: Newton needs more iterations because at turning point the solution Jacobian becomes singular, and nearby the quadratic convergence constant proportional to grows.
The earlier planar system shows the other side: robustness.
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 , where , pure Newton takes a huge first step and never recovers; damped Newton reaches root 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 function | Method | Requires | When |
|---|---|---|---|
optimize.brentq(f, a, b) | Brent (lesson variant) | sign-changing interval | default in one variable |
optimize.bisect(f, a, b) | bisection | interval | if is noisy or discontinuous |
optimize.newton(f, x0, fprime=df) | Newton | and good | cheap derivative and reliable start |
optimize.newton(f, x0) | secant | good | no derivative or bracket |
optimize.newton(f, x0, fprime, fprime2) | Halley (order 3) | and | very cheap derivatives |
optimize.root_scalar(f, method=...) | all above | method-dependent | unified interface |
optimize.root(F, x0, method="hybr") | Powell hybrid (MINPACK) | only | small and medium systems |
optimize.root(F, x0, method="krylov") | inexact Newton–Krylov | only | 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, , covered in lesson 16 on differentiating iterative solvers.
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
More than one answer may be correct.
Step 1 of 4. First ensure the step is defined. How do you choose an initial ?
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) / 2Summary
- Bisection: with a sign change, always converges one bit per evaluation; iterations for interval length . In floating point use midpoint , compare signs and stop when no doubles remain inside.
- Fixed point: converges locally if at rate ; order is that of the first nonzero derivative of at .
- Empirical order: 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 ; linear at rate for multiplicity ; far away it can diverge, cycle or jump among fractal basins.
- Secant and Brent: secant has order with one evaluation per step; Brent combines secant, inverse quadratic interpolation and bisection with a bracket guarantee.
- Systems: Newton solves with LU, is quadratic with invertible , and is globalized by line search on or trust regions. Broyden updates the Jacobian with rank one and converges superlinearly with one evaluation per iteration.
- Stopping: interval or step with , residual only scaled by conditioning, and always a maximum iteration count.