Gradient descent in one variable

Gradient descent needs only the derivative and a loop, and its behaviour depends strongly on the learning rate.

What to build

Run a fixed number of gradient-descent steps on a polynomial and print where you end up.

Requirements

  • Read the coefficients of f, then the start x0, the learning rate and the number of steps.
  • Repeat x ← x − rate × f′(x) for that many steps.
  • Print the final x and f(x), each to 4 decimal places.

Input

Line 1: 2 to 5 whole-number coefficients, highest power first. Line 2: x0 and rate (decimals), then steps (a whole number from 0 to 200).

Output

Two lines: x X and f F, to 4 decimal places.

Constraints

The coefficients are between -10 and 10. The result stays below one billion in size.

Example

Input:

1 -6 10
0 0.1 50

Output:

x 3.0000
f 1.0000

Why it works

Near a minimum the slope is small, so the steps shrink and x settles. If the rate is too large for the curve, each step overshoots and the distance from the minimum grows: with f = x² and rate 1.1, x is multiplied by −1.2 each time.

Examples

Example 1 · Input
1 -6 10
0 0.1 50
Expected output
x 3.0000
f 1.0000
Example 2 · Input
1 0 0
1 0.25 10
Expected output
x 0.0010
f 0.0000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Each step is x = x - rate * df(x). Compute df from the power rule on the coefficients.

Hint 2

Evaluate with Horner's rule, not with ** and big powers, so the results are repeatable.

Hint 3

Print x and f(x) with `:.4f`.

Solution

Show one correct solution (try it yourself first)
coeffs = [int(c) for c in input().split()]
x, rate, steps = input().split()
x, rate, steps = float(x), float(rate), int(steps)
n = len(coeffs) - 1

def f(t):
    total = 0.0
    for c in coeffs:
        total = total * t + c
    return total

def df(t):
    total = 0.0
    for i, c in enumerate(coeffs[:-1]):
        total = total * t + c * (n - i)
    return total

for _ in range(steps):
    x = x - rate * df(x)
print(f"x {x + 0.0:.4f}")
print(f"f {f(x) + 0.0:.4f}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Maxima, minima and gradient descent →