A chai stall sells cups at ₹10 and sells 200 a day. Raise the price, and each cup earns more, but fewer people buy. Charge too much and hardly anyone buys at all. Somewhere in between is the price that makes the most profit. How do you find it without trying every price?
Look at the slope. While raising the price still increases profit, the profit curve slopes upwards. Once raising it starts to lose money, the curve slopes downwards. At the very top, it's flat: the slope is zero. That one observation turns "find the best value" into "find where the derivative is zero", and it's the idea behind training every machine learning model, which is a search for the lowest point of a loss.
What you need first: what is a derivative? and derivative rules.
Key terms
- Maximum: a highest point of a function. Minimum: a lowest point. Together, extrema; maximum and minimum points are also called optima.
- Stationary point (or critical point): a point where the derivative is zero, so the curve is flat.
- Local minimum: lower than every point nearby, but not necessarily the lowest overall.
- Global minimum: the lowest point of the whole function.
- Second derivative: the derivative of the derivative. It says whether the slope is increasing (the curve bends upwards like a cup) or decreasing (bends downwards like a cap).
The chai stall
Suppose each cup costs the stall ₹5 to make, and for every ₹1 added to the price, 10 fewer cups sell. At price p, the stall sells 300 − 10*p* cups, and earns p − 5 on each. Profit is:
P(p) = (p − 5)(300 − 10*p*)
Plot it, with a short tangent line at three prices to show the slope:
import numpy as np
import matplotlib.pyplot as plt
def profit(p):
return (p - 5) * (300 - 10 * p)
def slope(f, x, h=1e-5):
return (f(x + h) - f(x - h)) / (2 * h)
prices = np.linspace(5, 30, 200)
fig, ax = plt.subplots(figsize=(8, 4.2))
ax.plot(prices, profit(prices), color="#1c1917", linewidth=2.5)
for p0, colour, label_at in [(10, "#0f766e", (10.8, 700)), (17.5, "#c2410c", (15.5, 1720)), (25, "#0f766e", (18.2, 700))]:
s = slope(profit, p0)
xs = np.array([p0 - 3, p0 + 3])
ax.plot(xs, profit(p0) + s * (xs - p0), color=colour, linewidth=2.5)
ax.annotate(f"₹{p0}: slope {s:.0f}", (p0, profit(p0)), xytext=label_at, fontsize=11)
ax.set_ylim(0, 1900)
ax.set_xlabel("Price per cup (₹)")
ax.set_ylabel("Daily profit (₹)")
ax.set_title("At the best price, the profit curve is flat")
plt.show()
slope is the central difference from the derivatives module: it measures the rise over a tiny step on each side.
At ₹10 the slope is positive: raising the price still adds profit. At ₹25 it's negative: raising the price loses profit, so you should lower it. At the top, the slope is exactly zero.
Find maxima and minima with the derivative
Instead of reading the top off a chart, use the derivative. Expand the profit:
P(p) = 300*p* − 10*p*² − 1,500 + 50*p* = −10*p*² + 350*p* − 1,500
Its derivative, with the power rule, is:
P′(p) = −20*p* + 350
Set it to zero and solve: −20*p* + 350 = 0, so p = 17.5. The best price is ₹17.50, giving a profit of P(17.5) = 12.5 × 125 = ₹1,562.50. Check against a brute-force search over 10,000 prices:
grid = np.linspace(5, 30, 10_001)
best = grid[np.argmax(profit(grid))]
print(f"brute force: best price ₹{best:.2f}, profit ₹{profit(best):,.2f}")
print(f"derivative: best price ₹17.50, profit ₹{profit(17.5):,.2f}")
brute force: best price ₹17.50, profit ₹1,562.50
derivative: best price ₹17.50, profit ₹1,562.50
np.argmax gives the position of the largest value in an array, so grid[np.argmax(...)] is the price with the highest profit.
The derivative found the exact answer with one line of algebra. Brute force needed 10,000 evaluations, and would need far more for a function of many variables.
Experiment: suppose customers are more sensitive to price. The stall still sells 200 cups at ₹10, but now every extra ₹1 loses 20 cups, so it sells 400 − 20*p*. Predict: should the best price go up or down? Then change the demand and run it:
def profit_sensitive(p):
return (p - 5) * (400 - 20 * p)
grid = np.linspace(5, 20, 15_001)
best = grid[np.argmax(profit_sensitive(grid))]
print(f"best price ₹{best:.2f}, profit ₹{profit_sensitive(best):,.2f}")
best price ₹12.50, profit ₹1,125.00
Down, to ₹12.50. When each price rise drives away more customers, it pays to stay cheaper. The derivative agrees: P(p) = (p − 5)(400 − 20*p*) = −20*p*² + 500*p* − 2,000, so P′(p) = −40*p* + 500, which is zero at p = 12.5.
Is it a top or a bottom?
A zero slope means flat, but flat could be a peak, a valley, or a ledge. Look at how the slope changes as you pass through the point:
- Slope goes from positive to negative (up, flat, down): a maximum.
- Slope goes from negative to positive (down, flat, up): a minimum.
- Slope keeps the same sign either side: neither, just a flat ledge (like x³ at 0).
The second derivative measures this change. For the profit, P″(p) = −20, which is negative: the slope is always falling, so the curve bends downwards like an upside-down cup, and the flat point is a maximum. A positive second derivative means the curve bends upwards like a cup, and the flat point is a minimum.
Local and global
A function can have several valleys. Each is a local minimum: lower than its neighbours. Only the deepest is the global minimum. Here's a curve with two:
def bumpy(x):
return x**4 - 4 * x**2 + x
xs = np.linspace(-2.3, 2.3, 400)
fig, ax = plt.subplots(figsize=(8, 3.8))
ax.plot(xs, bumpy(xs), color="#1c1917", linewidth=2.5)
for x0, label, label_at in [(-1.47, "global minimum", (-1.3, -5.8)), (1.35, "local minimum", (0.75, -4.2)), (0.13, "local maximum", (-0.4, 1.4))]:
ax.plot(x0, bumpy(x0), "o", color="#c2410c", markersize=9)
ax.annotate(label, (x0, bumpy(x0)), xytext=label_at, fontsize=11)
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
ax.set_title("Two valleys: only one is the lowest")
plt.show()
Check the slope at the three marked points. They were read off the chart, so expect values close to zero rather than exactly zero:
print([round(slope(bumpy, x0), 2) for x0 in (-1.47, 0.13, 1.35)])
[0.05, -0.03, 0.04]
The derivative is zero at all three points, so "slope is zero" finds candidates, not answers. To find the global minimum, compare the function's value at every candidate (and at the ends of the range, if there are ends).
This matters for machine learning. A model that walks downhill from a starting point, as gradient descent does, can settle in a local minimum. For linear and logistic regression, the loss has only one valley (it's convex), so this can't happen. For neural networks it can, though in practice their many local minima tend to be about equally good.
The mean minimises squared error
Here's a result you'll use again and again. You must predict one number, c, for every value in a dataset, and you're judged by the sum of squared errors: Σ (y − c)². Which c is best?
Take the derivative with respect to c. Each term (y − c)² has derivative −2(y − c) by the chain rule, so:
d/d*c* Σ (y − c)² = −2 Σ (y − c)
Set it to zero: Σ (y − c) = 0, so Σ y = n × c, and c = Σ y ÷ n. The best single prediction under squared error is the mean. Check it on delivery times:
times = np.array([22, 25, 19, 31, 24, 27, 58, 23])
def sse(c):
return ((times - c) ** 2).sum()
def sae(c):
return np.abs(times - c).sum()
cs = np.linspace(15, 45, 6001) # steps of 0.005, so 28.625 is on the grid
print("minimises squared error: ", cs[np.argmin([sse(c) for c in cs])], " mean: ", times.mean())
print("minimises absolute error:", cs[np.argmin([sae(c) for c in cs])], " median:", np.median(times))
minimises squared error: 28.625 mean: 28.625
minimises absolute error: 24.0 median: 24.5
The squared-error minimum lands exactly on the mean. And the absolute error (Σ |y − c|) is minimised by the median instead (any value between the two middle times gives the same total, so the search finds the first of them). That's why the mean and median behave differently with outliers: they're the answers to two different "best guess" questions. It's also why the choice of loss function changes what a model learns.
When you can't solve it with algebra
The chai stall and the mean had neat answers: set the derivative to zero and solve. Most real models have thousands or millions of weights, and the equation "derivative = 0" can't be solved by hand. Then you use the slope as a direction: if it's positive, step left; if negative, step right; repeat until it's flat. That's gradient descent, and with many variables the slope becomes the gradient.
Where machine learning uses this
- Training is minimisation. Every model is fitted by finding the weights where the loss is lowest.
- Closed-form solutions: for linear regression, setting the derivatives of squared error to zero gives an exact formula for the best weights (the normal equation).
- Choosing the loss chooses the answer: squared error leads to means, absolute error to medians, as you just saw.
- Local minima are why neural network training can depend on the random starting weights.
Common mistakes
- Assuming every flat point is a minimum. Check the slope's sign change or the second derivative.
- Stopping at a local minimum. Compare all candidates, and the ends of the range.
- Forgetting the range. If price must be at most ₹15, the best allowed price is at the edge, ₹15, where the slope isn't zero.
- Solving when you should search. Most ML losses need gradient descent, not algebra.
Practice
- Find the minimum of f(x) = x² − 6*x* + 11. Is it a minimum or a maximum, and how do you know?
Show the answer
f′(x) = 2*x* − 6 = 0 gives x = 3, and f(3) = 9 − 18 + 11 = 2. f″(x) = 2 is positive, so the curve bends upwards: it's a minimum.
- Predict, then check: if the cost per cup rises from ₹5 to ₹9, does the best price rise by the full ₹4?
Show the answer
No, by half: ₹2. The stall shares the extra cost with customers, because raising the price also loses sales.
grid = np.linspace(9, 30, 21_001)
new_profit = (grid - 9) * (300 - 10 * grid)
print(round(grid[np.argmax(new_profit)], 2))
19.5
With algebra: P(p) = (p − 9)(300 − 10*p*) has P′(p) = −20*p* + 390, which is zero at p = 19.5.
- A ball's height is h(t) = 20*t* − 5*t*² metres after t seconds. When is it highest, and how high does it go?
Show the answer
h′(t) = 20 − 10*t* = 0 at t = 2 seconds. h(2) = 40 − 20 = 20 metres.
- Explain in your own words why the derivative is zero at the bottom of a valley.
Show the answer
Just left of the bottom, the curve goes down as you move right (negative slope); just right of it, the curve goes up (positive slope). The slope changes from negative to positive, so at the bottom it passes through zero: the curve is momentarily flat.
- A model predicts the same delivery time for every order. Using squared error, it predicts 28.6 minutes; using absolute error, it predicts 24.5. Why are they different, and which is more affected by the 58-minute order?
Show the answer
Squared error is minimised by the mean and absolute error by the median. The 58-minute order pulls the mean up but barely moves the median, so the squared-error prediction is the one affected.
Interview questions
How do you find the minimum of a differentiable function?
Find stationary points where the derivative is zero, then classify them with the second derivative (positive: minimum) or the sign change of the first derivative, and compare values, including boundaries, to find the global minimum. When the equation can't be solved analytically, use iterative methods such as gradient descent or Newton's method.
Why does the mean minimise squared error?
The derivative of Σ(yᵢ − c)² with respect to c is −2Σ(yᵢ − c). Setting it to zero gives c = mean(y), and the second derivative 2n > 0 confirms a minimum. Absolute error is minimised by the median instead.
Key takeaways
- At a maximum or minimum of a smooth function, the slope is zero: the curve is flat.
- Solve "derivative = 0" to find candidates, then check which are peaks, valleys or ledges.
- The second derivative tells the shape: negative bends down (maximum), positive bends up (minimum).
- Local minima are lowest nearby; the global minimum is lowest overall. Compare all candidates.
- The mean minimises squared error and the median minimises absolute error; most models are trained by searching for a minimum.
Frequently asked questions
What if the function has a sharp corner?
At a corner, like |x| at 0, there's no derivative, yet it can still be a minimum. Check corners and the ends of the range separately. Absolute error has corners, which is why it's minimised by the median rather than by solving an equation.
Do I need the second derivative in ML?
Rarely by hand. It describes curvature, which advanced optimisers use, and it's the idea behind convexity: a loss with a positive second derivative everywhere has a single valley.
What does "optimisation" mean?
Finding the input that gives the best (highest or lowest) output. In ML it almost always means minimising a loss.
What to learn next
- Move to functions of many inputs in functions of several variables.
- Learn the slope in one direction at a time in partial derivatives explained.
- See minimisation used for real in gradient descent explained.