One-dimensional optimization
- •
Minimum versus root
- •
Golden-section search
- •
Parabolic and Newton steps
- •
Python: cached golden-section search
- •
standalone standard-library example; explicit status distinguishes convergence from exhausting the limit
- •
import math def golden_min(f, a, b, tol=1e-8, max_iter=200): if not all(math.isfinite(v) for v in (a, b, tol)) or a >= b or tol <= 0: raise ValueError("finite ordered bounds and positive tolerance required") if not isinstance(max_iter, int) or max_iter < 1: raise ValueError("positive integer iteration limit required") def evaluate(x): value = f(x) if not math.isfinite(value): raise ValueError("nonfinite objective") return value phi = (math.sqrt(5) - 1)/2 c, d = b - phi*(b-a), a + phi*(b-a) fc, fd = evaluate(c), evaluate(d) it = 0 while b-a > tol and it < max_iter: if fc <= fd: b, d, fd = d, c, fc c = b - phi*(b-a) fc = evaluate(c) else: a, c, fc = c, d, fd d = a + phi*(b-a) fd = evaluate(d) it += 1 status = "converged" if b-a <= tol else "iteration_limit" x = (a+b)/2 return x, evaluate(x), (a, b), it, status x, value, bracket, it, status = golden_min(lambda x: x*x - 4*math.sin(x), 0., 3.) assert status == "converged" and bracket[1]-bracket[0] <= 1e-8 assert abs(x - 1.0298665293) < 5e-8 assert abs(value + 2.368296005) < 1e-8 print("minimum:", x, value, "reductions:", it)
- •