Delivery Time Nudge

Easygradient descentAlso known as One Step of Gradient Descent for Linear Regression

A pizza place promises customers a delivery time. Its model is a straight line: minutes = w · distance + b, where w is minutes per kilometre and b is the fixed time to bake and pack. Each night it looks at the day's real deliveries and adjusts w and b a little so tomorrow's promises are closer.

That small adjustment is one step of gradient descent: work out which way each number should move to shrink the average squared miss, then move it a small amount that way. Training any neural network is this same step repeated millions of times, with far more numbers.

Your task

Write trainStep(distances, minutes, w, b, rate). The loss is the mean squared error L = (1/n) · Σ (w·xᵢ + b − yᵢ)², where xᵢ is distances[i] and yᵢ is minutes[i]. Its gradients are:

  • dL/dw = (2/n) · Σ (w·xᵢ + b − yᵢ) · xᵢ
  • dL/db = (2/n) · Σ (w·xᵢ + b − yᵢ)

Compute both gradients using the current w and b, then return [w − rate · dL/dw, b − rate · dL/db].

trainStep(distances: float[], minutes: float[], w: float, b: float, rate: float) → float[] Numbers are accepted within 1e-6.

Examples

Example 1
Input
distances = [1, 2, 3]
minutes = [5, 7, 9]
w = 1
b = 1
rate = 0.1
Output
[2.7333333333333334, 1.8]
Why

Predictions are 2, 3, 4 and the truth is 5, 7, 9, so the errors (prediction minus truth) are -3, -4, -5. dL/dw = (2/3)(-3·1 - 4·2 - 5·3) = (2/3)(-26) = -17.333…, dL/db = (2/3)(-12) = -8. Both are negative, so both numbers go up: w = 1 + 1.7333… = 2.7333…, b = 1 + 0.8 = 1.8.

Example 2
Input
distances = [2, 4]
minutes = [10, 16]
w = 3
b = 4
rate = 0.05
Output
[3, 4]
Why

The line 3·x + 4 gives exactly 10 and 16. Every error is 0, so both gradients are 0 and nothing moves. A perfect fit is a flat spot in the loss.

Constraints

  • 1 ≤ n = distances.length = minutes.length ≤ 10,000
  • -1,000 ≤ distances[i], minutes[i], w, b ≤ 1,000
  • 0 ≤ rate ≤ 1
  • Answers within 0.000001 of the expected values (or relatively that close) are accepted.
Start with brute force

Without the gradient formula you could probe: try w a tiny bit bigger and a tiny bit smaller, compute the loss each time, and see which is lower. Do the same for b. That costs several full passes over the data per number, and with millions of numbers in a real model it is hopeless. It also only approximates the slope.

The formula gives the exact slope for every number in a single pass. That is the whole reason calculus matters for training: the gradient tells you which way is downhill for all the weights at once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code