Delivery Time Nudge

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

A pizza place predicts delivery time with 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 nudges w and b using the day's real deliveries.

That nudge is one step of gradient descent: find which way each number should move to shrink the average squared miss, then move it a little that way. Training a neural network is this step repeated millions of times.

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 2, 3, 4 against truth 5, 7, 9 give errors -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

3·x + 4 gives exactly 10 and 16. Every error is 0, so both gradients are 0 and nothing moves.

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 formula you could probe: nudge w up and down a tiny bit, compute the loss each time, and keep the lower side. You would do the same for b. That costs several full passes per number, which is impractical for a model with millions of numbers, and it only approximates the slope. The formula gives the exact slope for every number in one pass.

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