Numerical methods

Gradient descent

Gradient descent walks downhill: from a point xx it steps against the gradient, x←x−t ∇f(x)x \leftarrow x - t\,\nabla f(x). gradientDescent runs the method and keeps its table. When ff is built from ++, −-, ×\times, ÷\div and integer powers, every iterate, value, gradient and step is an exact fraction, so the table is what the method does with no rounding at all; otherwise it runs in floating point. The result is labelled simulated: it shows the method from one start and proves nothing about a minimum. For a certified minimum use extrema on one variable or lagrange with constraints.

const r = gradientDescent("x^2 + 4*y^2", ["1", "1"], { step: "1/10", steps: 2 });
r.iterations.map((row) => row.x);   // [[1, 1], [4/5, 1/5], [16/25, 1/25]]
r.simulated;                          // true

Choosing the step

  • Fixed (method: "fixed", step = 1/10 by default). The same tt every time. For f=x2+4y2f = x^2 + 4y^2 a step above 1/41/4 makes the yy coordinate grow: the step must be below 2/L2/L where LL is the largest curvature.
  • Backtracking ("backtracking"). Start at step (default 1) and halve until the Armijo condition f(x−tg)≤f(x)−c t ∣g∣2f(x - t g) \le f(x) - c\,t\,|g|^2 holds, with cc = armijo (default 1/21/2). Each step is then guaranteed to decrease ff by a fixed fraction of what the slope promised.
  • Exact line search ("exact"), for a quadratic f=12xTHx+bTx+cf = \tfrac12 x^{\mathsf T} H x + b^{\mathsf T}x + c. Along x−tgx - t g the value is a parabola in tt, minimised at
t∗=gTggTHg. t^* = \frac{g^{\mathsf T} g}{g^{\mathsf T} H g}.

Successive gradients are then perpendicular, which is why the path zigzags when the level sets are long ellipses. With exact fractions this is visible exactly: the dot product of consecutive gradients is 0, not a small number.

callreturns
gradientDescent(f, start, { variables, method = "fixed", step, steps = 10, armijo = "1/2" }){ simulated: true, method, variables, iterations: [{ n, x, fx, gradient, step }], final, value, exact }
Try itEdit the code and run it with @ratmath/analytic and Core's R, Rational, RationalInterval in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs