Ternary Search & Continuous Bisection
Unimodal functions, golden-section search and searching over real numbers.
Binary search needs a yes/no question that flips once. To find the top of a hill you cannot ask "is the top to my left?" directly, but two nearby measurements answer it: if the ground still rises, the peak lies ahead. That one idea gives ternary search; golden-section search, which needs only one new measurement per step; and bisection, which pins down a root of any continuous function to full machine precision in about sixty halvings.
What you’ll learn
- Prove that ternary search finds the maximum of a strictly unimodal function, and show that flat stretches make the problem as hard as searching an unsorted array.
- Compare ternary search, bisection on the slope and golden-section search by evaluations per digit of precision, and derive the golden ratio from the requirement that one probe be reused.
- State Kiefer's theorem that Fibonacci search is minimax-optimal, and show that golden-section search comes within about 17% of it.
- Find roots by bisection with a certified error, choose iteration counts that survive floating point, and search exactly over the bit patterns of doubles.
Unimodal functions and ternary search
Probe two interior points . If , the maximum cannot lie at or left of : from such an the function would decrease through to , contradicting . Symmetrically, rules out everything at or right of , and puts strictly between them, so either cut is safe.
With the probes at the thirds, ternary search keeps of the interval at a cost of two evaluations per step. On the integers, a cheaper variant compares neighbors: is a monotone predicate (true while the function climbs), so ordinary binary search on the slope finds the peak.
def ternary_max(f, lo, hi, iters=100):
"""Maximum point of a strictly unimodal f on the reals [lo, hi]."""
for _ in range(iters): # each step keeps 2/3 of the interval
m1 = lo + (hi - lo) / 3
m2 = hi - (hi - lo) / 3
if f(m1) < f(m2):
lo = m1 # the maximum is not in [lo, m1)
else:
hi = m2 # the maximum is not in (m2, hi]
return (lo + hi) / 2
def argmax_int(f, lo, hi):
"""Maximum point of a strictly unimodal f on the integers lo..hi."""
while lo < hi:
mid = lo + (hi - lo) // 2
if f(mid) < f(mid + 1):
lo = mid + 1 # still climbing: the peak is right of mid
else:
hi = mid # descending: the peak is mid or left of it
return loargmax_int is the lower-bound loop on the predicate , two evaluations per halving. Both functions were tested on random strictly unimodal inputs.
Golden-section search: one evaluation per step
Ternary search throws both probes away after every step. Instead, place the probes so that the surviving one lands exactly where a probe of the next interval belongs. Then each step costs a single new evaluation.
Scale the interval to and put the probes symmetrically at and , with . If the comparison drops , the new interval needs probes at and . The old probe survives inside it, and reusing it as the new right probe requires
So each step shrinks the interval by the factor for one evaluation. Per evaluation, the three methods shrink the interval by
To shrink an interval by a factor , golden-section search needs about evaluations, bisection on the slope , and ternary search , more than twice as many as golden section.
import math
def golden_max(f, lo, hi, iters=80):
"""Golden-section search for the maximum of a strictly unimodal f on [lo, hi]."""
r = (math.sqrt(5) - 1) / 2 # 0.618..., the solution of r * r = 1 - r
x1, x2 = hi - r * (hi - lo), lo + r * (hi - lo)
f1, f2 = f(x1), f(x2)
for _ in range(iters): # one new evaluation per step
if f1 < f2: # drop [lo, x1): x2 becomes the new x1
lo, x1, f1 = x1, x2, f2
x2 = lo + r * (hi - lo)
f2 = f(x2)
else: # drop (x2, hi]: x1 becomes the new x2
hi, x2, f2 = x2, x1, f1
x1 = hi - r * (hi - lo)
f1 = f(x1)
return (lo + hi) / 2Eighty steps shrink the interval by , below double-precision resolution relative to the starting width. When evaluating is expensive (a simulation, a physical experiment), saving half of the evaluations is the whole point.
Fibonacci search is optimal
Let be the length of the interval after evaluations, with one earlier probe inside it. With symmetric probes , both possible survivors, and , have length , and the probe kept inside the survivor sits at distance from its far end. That distance is the next survivor's length:
The last comparison can at best halve the final interval, with its two probes side by side in the middle, so . Unrolling the recurrence back to the start:
Kiefer's lower bound shows that no placement, symmetric or not, does better: an adversary keeps the longer candidate interval, which forces the same recurrence. Golden section uses the limiting ratio from the start, so after evaluations it has shrunk the interval by only :
You may evaluate a strictly unimodal function 10 times. By what factor can Fibonacci search guarantee to shrink the interval of uncertainty?
- , one halving per evaluation
- About 7.6, like five steps of ternary search
- About 76, like golden-section search
Show the answer
D.
With evaluations the guaranteed factor is , here . Golden-section search achieves , about 17% less, and ternary search, at two evaluations per step, only . By Kiefer's theorem, no strategy guarantees more than 89.
Bisection: roots with a certificate
Root finding is binary search on a sign. If is continuous on with , the intermediate value theorem guarantees a root in . The bisection method keeps that situation as its invariant: evaluate the midpoint, and keep the half whose ends still straddle zero. Like the peak finder, it needs no monotonicity, only a sign change that halving preserves.
Invariant. The ends straddle zero and is continuous, so a root lies in :
Certified error. After halvings the bracket has width , and every point in it is that close to a root: a guarantee, not an estimate. Precision therefore costs
Optimality. Bisection gains one bit of the root per evaluation, and in the worst case nothing does better: among methods that learn about only through its values, bisection minimizes the worst-case error for a given number of evaluations (Sikorski, 1982).
def bisect_root(f, lo, hi, iters=100):
"""A root of a continuous f with f(lo) < 0 <= f(hi)."""
for _ in range(iters): # a fixed count, never "while hi - lo > eps"
mid = (lo + hi) / 2
if f(mid) < 0:
lo = mid # invariant: f(lo) < 0 <= f(hi)
else:
hi = mid
return hiTested on for random over the bracket . No derivative, no smoothness: continuity and one sign change are all it needs.
Bisection starts on the bracket . How many halvings does it take until the bracket is narrower than ?
Show the answer
30
The width after halvings is , and it drops below once . Since and , that takes : three halvings per decimal digit, roughly.
Faster methods trade the guarantee for speed. Newton's method roughly doubles the number of correct digits per step near a simple root, but it can diverge or cycle far from one. Brent's method (1973) mixes interpolation steps with bisection steps, so it converges whenever bisection would, usually far faster. The ITP method (Oliveira & Takahashi, 2021) keeps bisection's worst-case number of evaluations, up to a slack you choose, while converging superlinearly on well-behaved functions.
Floating point, and searching the bits
For an exact answer, search over the doubles themselves. For , the IEEE 754 bit patterns, read as 64-bit integers, are ordered exactly like the values. So an integer binary search over bit patterns finds the last double satisfying a monotone condition in at most 63 probes, whatever magnitudes are involved.
import math, struct
def as_int(x): # the IEEE 754 bit pattern of a double, as an integer
return struct.unpack('<q', struct.pack('<d', x))[0]
def as_float(b):
return struct.unpack('<d', struct.pack('<q', b))[0]
def last_double(ok, lo=0.0, hi=math.inf):
"""Largest double x in [lo, hi) with ok(x); ok must be true ... true false ... false, ok(lo) true."""
a, b = as_int(lo), as_int(hi) # for x >= 0, bit patterns are ordered like the values
while b - a > 1:
m = a + (b - a) // 2
if ok(as_float(m)):
a = m
else:
b = m
return as_float(a)
print(last_double(lambda x: x * x <= 2.0)) # 1.414213562373095, after 63 probesThe answer is the largest double whose floating-point square is at most 2. It sits one unit in the last place below math.sqrt(2), the correctly rounded root, whose computed square exceeds 2.
Recognizing unimodal problems. Ternary or golden-section search on the reals, and bisection on the slope on the integers, fit problems whose objective is unimodal in a single parameter: the moment when points moving at constant velocities are closest together (each pairwise distance is convex in time, and so is their maximum), the price that maximizes revenue under a unimodal demand curve, or the split point of a convex cost. Sums and maxima of convex functions stay convex, but a sum of unimodal functions need not be unimodal, so check before you search.
Key takeaways
- On a strictly unimodal function, comparing two values discards a part of the interval that cannot hold the extremum: ternary search keeps per step, and bisection on the slope halves the interval with two evaluations.
- Flat stretches away from the extremum make the search as hard as scanning an unsorted array; convex functions are safe, and sums and maxima of convex functions are convex.
- Golden-section search reuses one probe per step thanks to , costing about evaluations to shrink an interval -fold; Fibonacci search is optimal (Kiefer, 1953), and golden section is within about 17% of it.
- Bisection keeps the sign invariant and certifies an error of after steps; in floating point, run a fixed number of halvings or bisect the bit patterns of doubles.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why can no algorithm find the maximum of every weakly unimodal function (flat stretches allowed) on points with evaluations?
- Floating-point rounding makes equal values unreliable
- The function that is 0 everywhere except a single 1 is weakly unimodal, and an adversary can answer 0 to every probe until the last
- Ternary search needs two evaluations per step
- Weakly unimodal functions can have several separate maxima
Show the answer
B. The function that is 0 everywhere except a single 1 is weakly unimodal, and an adversary can answer 0 to every probe until the last
Every probe of that function returns 0 until it hits the 1, and the answers carry no hint of direction, so the adversary can place the 1 at whichever point is probed last. Any algorithm then needs evaluations in the worst case, as for an unsorted array.
Golden-section search keeps the fraction of the interval per step. Why that value?
- It makes the surviving probe land exactly where the next step needs one, since , so each step costs one new evaluation
- It minimizes floating-point rounding errors
- It splits the interval into equal thirds
- Any above works equally well; the golden ratio is tradition
Show the answer
A. It makes the surviving probe land exactly where the next step needs one, since , so each step costs one new evaluation
After dropping one end, the old interior probe must become an interior probe of the new interval at the same relative position. Solving gives , and the method then pays one evaluation per step instead of two.
A bisection loop runs while hi - lo > 1e-9 in double precision, and the root is near . What happens?
- It stops after about 60 halvings
- It stops after one halving
- It raises an overflow error
- It never stops: near , consecutive doubles are about apart, so the width cannot fall below
Show the answer
D. It never stops: near , consecutive doubles are about apart, so the width cannot fall below
Doubles carry 53 significant bits, so near their spacing is . Once lo and hi are adjacent doubles, the midpoint equals one of them and the width stays at forever. A fixed number of halvings avoids the trap.
Which function can ternary search minimize safely on an interval?
- The sum of two unimodal functions
- Any function whose global minimum is unique
- The largest pairwise distance among points moving in straight lines at constant speeds, as a function of time
- A unimodal function with a flat stretch above its minimum
Show the answer
C. The largest pairwise distance among points moving in straight lines at constant speeds, as a function of time
Each pairwise distance is the norm of an affine function of , hence convex, and a maximum of convex functions is convex. A convex function is unimodal, and flat stretches can only occur at its minimum, so the comparisons always point the right way.
Further reading
- J. Kiefer, "Sequential minimax search for a maximum," Proceedings of the American Mathematical Society 4 (1953), 502–506.
- R. P. Brent, Algorithms for Minimization without Derivatives (Prentice-Hall, 1973).
- I. F. D. Oliveira & R. H. C. Takahashi, "An enhancement of the bisection method average performance preserving minmax optimality," ACM Transactions on Mathematical Software 47(1) (2021).
- W. H. Press, S. A. Teukolsky, W. T. Vetterling & B. P. Flannery, Numerical Recipes: The Art of Scientific Computing, 3rd ed. (Cambridge University Press, 2007), chapters 9 and 10.