Working out every derivative from first principles is like walking everywhere: you'll get there, but it's slow. In the last lesson you noticed a pattern in all the results: x² → 2x, x³ → 3x², 1/x → −1/x². Patterns like that are shortcuts, and calculus has a handful of them, called derivative rules. With just the first three, you can differentiate any polynomial in a few seconds.
This lesson explains the three basic derivative rules: the power rule (with a picture that shows why it works), the constant multiple rule and the sum rule. Then it uses them together to find the best weight for a simple machine learning model, exactly, with no trial and error.
What you need first: the derivative from first principles and exponents and powers, including negative and fractional powers.
Key terms
- Power rule: the derivative of xⁿ is n × xⁿ⁻¹.
- Constant rule: the derivative of a constant number is 0.
- Constant multiple rule: the derivative of c × f(x) is c × f′(x).
- Sum rule: the derivative of f(x) + g(x) is f′(x) + g′(x).
- Polynomial: a sum of powers of x with number coefficients, such as 3x⁴ − 5x² + 7.
The power rule
d/dx (xⁿ) = n × xⁿ⁻¹
Read it as "the derivative of x to the n is n times x to the n minus 1". In words: bring the power down in front, then take one off the power.
| Function | Bring the power down | Take one off | Derivative |
|---|---|---|---|
| x⁵ | 5 × x... | x⁴ | 5x⁴ |
| x² | 2 × x... | x¹ | 2x |
| x | 1 × x... | x⁰ = 1 | 1 |
| x⁻¹ = 1/x | −1 × x... | x⁻² | −1/x² |
| x^(1/2) = √x | ½ × x... | x^(−1/2) | 1/(2√x) |
It works for any power: whole numbers, negative numbers and fractions.
Why it works: a growing square
Picture a square with side x. Its area is x². Now make the side a tiny bit longer, by dx. How much extra area do you get?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
x, dx = 3.0, 0.5
fig, ax = plt.subplots(figsize=(6, 6))
ax.add_patch(Rectangle((0, 0), x, x, facecolor="#dbeafe", edgecolor="black"))
ax.add_patch(Rectangle((x, 0), dx, x, facecolor="#fdba74", edgecolor="black"))
ax.add_patch(Rectangle((0, x), x, dx, facecolor="#fdba74", edgecolor="black"))
ax.add_patch(Rectangle((x, x), dx, dx, facecolor="#dc2626", edgecolor="black"))
ax.text(x / 2, x / 2, "x²\n(the old area)", ha="center", va="center", fontsize=13)
ax.text(x + dx / 2, x / 2, "x · dx", ha="center", va="center", rotation=90, fontsize=12)
ax.text(x / 2, x + dx / 2, "x · dx", ha="center", va="center", fontsize=12)
ax.text(x + dx + 0.08, x + dx / 2, "dx² (tiny)", va="center", fontsize=11, color="#dc2626")
ax.set_xlim(-0.2, 4.6)
ax.set_ylim(-0.2, 4.0)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("Grow a square's side by dx: the area grows by 2 · x · dx + dx²")
plt.show()
The new area is the old square, plus two strips of size x × dx, plus a tiny corner of size dx × dx. Divide the extra area by the extra length dx:
(2x · dx + dx²) ÷ dx = 2x + dx
As dx shrinks, the corner becomes negligible (it's a tiny number squared), and the rate is 2x. The "2" in 2x is the two strips. For a cube with side x, volume x³, growing the side adds three thin slabs of size x² × dx, one on each of three faces, so the derivative is 3x². The power counts how many faces grow.
The constant rule
d/dx (c) = 0, for any number c.
A constant never changes, so its rate of change is 0: its graph is a flat line. d/dx (7) = 0.
The constant multiple rule
d/dx (c × f(x)) = c × f′(x)
Multiplying a function by 3 stretches its graph 3 times taller, so every slope becomes 3 times steeper. d/dx (3x²) = 3 × 2x = 6x.
The sum rule
d/dx (f(x) + g(x)) = f′(x) + g′(x)
Walking along a moving walkway at an airport: if you walk at 1.5 m/s and the walkway moves at 0.5 m/s, your speed is 1.5 + 0.5 = 2 m/s. When two quantities add up, their rates of change add up too. The same works for subtraction.
Putting them together
Differentiate f(x) = 3x⁴ − 5x² + 7x − 2, one term at a time:
| Term | Rule | Derivative |
|---|---|---|
| 3x⁴ | Constant multiple and power: 3 × 4x³ | 12x³ |
| −5x² | −5 × 2x | −10x |
| 7x | 7 × 1 | 7 |
| −2 | Constant | 0 |
So f′(x) = 12x³ − 10x + 7. Check it against a numerical slope at many points at once:
def f(x):
return 3 * x ** 4 - 5 * x ** 2 + 7 * x - 2
def f_prime(x):
return 12 * x ** 3 - 10 * x + 7
xs = np.linspace(-2, 2, 9)
numeric = (f(xs + 1e-6) - f(xs - 1e-6)) / 2e-6 # a two-sided slope, more accurate
print("x: ", xs)
print("formula: ", f_prime(xs))
print("numeric: ", np.round(numeric, 4))
print(f"largest difference: {np.max(np.abs(numeric - f_prime(xs))):.2e}")
x: [-2. -1.5 -1. -0.5 0. 0.5 1. 1.5 2. ]
formula: [-69. -18.5 5. 10.5 7. 3.5 9. 32.5 83. ]
numeric: [-69. -18.5 5. 10.5 7. 3.5 9. 32.5 83. ]
largest difference: 3.61e-09
Rewrite before you differentiate. Fractions and roots of x become powers first:
- 4/x² = 4x⁻² → 4 × (−2)x⁻³ = −8/x³
- 6√x = 6x^(1/2) → 6 × ½x^(−1/2) = 3/√x
- (x + 1)² = x² + 2x + 1 → 2x + 2 (expand first; the chain rule gives a faster way later)
Finding the lowest point exactly
In the last lesson, the lowest point of a model's error was where its derivative was 0. With the rules, finding it takes seconds. Take L(w) = 3w² − 12w + 20:
- L′(w) = 6w − 12.
- Set it to 0: 6w − 12 = 0, so w = 2.
- The lowest error is L(2) = 12 − 24 + 20 = 8.
def L(w):
return 3 * w ** 2 - 12 * w + 20
ws = np.linspace(-0.5, 4.5, 200)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(ws, L(ws), color="black", linewidth=2.5, label="L(w) = 3w² − 12w + 20")
for w0, colour, offset in [(0.5, "#c2410c", (12, 6)), (2, "#1f5fbf", (-22, 10)), (3.5, "#c2410c", (12, -14))]:
slope = 6 * w0 - 12
seg = np.array([w0 - 0.7, w0 + 0.7])
ax.plot(seg, L(w0) + slope * (seg - w0), color=colour, linewidth=2)
ax.annotate(f"L′ = {slope:g}", (w0, L(w0)), textcoords="offset points", xytext=offset, color=colour)
ax.set_xlabel("weight w")
ax.set_ylabel("error L(w)")
ax.set_title("The lowest error is where the derivative is 0")
ax.legend(loc="upper center")
plt.show()
The best weight for real data
A model predicts y = w × x. With data points (1, 2), (2, 4) and (3, 7), its mean squared error is:
L(w) = ⅓[(w − 2)² + (2w − 4)² + (3w − 7)²]
Expand each bracket and add them up: L(w) = ⅓[14w² − 62w + 69]. By the rules, L′(w) = ⅓(28w − 62). Setting it to 0 gives w = 62/28 = 31/14 ≈ 2.214: the best possible weight, found exactly. Notice that 31 = 1 × 2 + 2 × 4 + 3 × 7 (the sum of x × y) and 14 = 1² + 2² + 3² (the sum of x²). That's the least squares formula for a line through the origin, and you just derived it.
x_data = np.array([1.0, 2.0, 3.0])
y_data = np.array([2.0, 4.0, 7.0])
best_w = np.sum(x_data * y_data) / np.sum(x_data ** 2)
print(f"best w from the derivative: {best_w:.4f}")
ws = np.linspace(0, 4, 400001)
errors = [np.mean((w * x_data - y_data) ** 2) for w in ws[::100]]
print(f"best w from trying 4,001 values: {ws[::100][np.argmin(errors)]:.4f}")
best w from the derivative: 2.2143
best w from trying 4,001 values: 2.2140
Where machine learning uses these rules
- Linear regression: the error is a sum of squared terms, so its derivative comes from the power, constant multiple and sum rules; setting it to 0 gives the least squares solution.
- Gradient descent: each step uses the derivative of the loss; the sum rule means the derivative of a total loss over many rows is the sum of the derivatives for each row, which is what makes mini-batch training work.
- Regularisation: Ridge adds alpha × w² to the loss, and by the power rule its derivative adds 2 × alpha × w, pulling every weight towards zero; see regularisation explained.
Common mistakes
- Forgetting to reduce the power. d/dx (x³) is 3x², not 3x³.
- Applying the power rule to a constant power base, such as 2ˣ. The power rule needs the variable in the base (xⁿ). 2ˣ is an exponential; see derivatives of exponentials and logarithms.
- Differentiating a product term by term. (x² + 1)(x − 3) isn't (2x)(1). Expand it first, or use the product rule.
- Not rewriting roots and fractions. 1/x³ must become x⁻³ before using the power rule: the derivative is −3x⁻⁴.
Practice
- Differentiate f(x) = 5x³ − 2x² + 4.
Show the answer
f′(x) = 15x² − 4x. (The constant 4 becomes 0.)
- Differentiate g(x) = 2/x + 3√x, rewriting as powers first.
Show the answer
g(x) = 2x⁻¹ + 3x^(1/2), so g′(x) = −2x⁻² + (3/2)x^(−1/2) = −2/x² + 3/(2√x).
- Find the value of w that minimises L(w) = 2w² − 10w + 3, and check it in Python.
Show the answer
L′(w) = 4w − 10 = 0, so w = 2.5.
L2 = lambda w: 2 * w ** 2 - 10 * w + 3
ws = np.linspace(0, 5, 50001)
print(ws[np.argmin(L2(ws))])
2.5
- With Ridge regularisation, a model's loss becomes L(w) = (2w − 5)² + 0.5w². Find the best w. How does it compare with 2.5, the best w without the penalty?
Show the answer
Expand: L(w) = 4w² − 20w + 25 + 0.5w² = 4.5w² − 20w + 25. L′(w) = 9w − 20 = 0, so w = 20/9 ≈ 2.222. The penalty pulls the weight from 2.5 towards zero: that's regularisation, seen through derivatives.
Interview questions
Derive the least squares solution for a line through the origin.
The loss is L(w) = (1/n) Σ (w xᵢ − yᵢ)². Its derivative is (2/n) Σ (w xᵢ − yᵢ) xᵢ. Setting it to zero gives w Σ xᵢ² = Σ xᵢ yᵢ, so w = Σ xᵢ yᵢ ÷ Σ xᵢ². With several features, the same steps in matrix form give the normal equation w = (XᵀX)⁻¹ Xᵀy.
How does L2 regularisation change the gradient?
Adding λw² to the loss adds 2λw to the gradient. Each gradient descent step therefore shrinks the weight by a fraction proportional to its size, before the data's own gradient is applied, which is why L2 regularisation is also called weight decay.
Key takeaways
- Power rule: d/dx (xⁿ) = n xⁿ⁻¹; bring the power down, take one off. It works for any power.
- The derivative of a constant is 0; constants multiplying a function stay put: (c f)′ = c f′.
- Sum rule: differentiate a sum term by term.
- Rewrite roots and fractions as powers before differentiating.
- Setting the derivative to 0 finds the best weight exactly; for a line through the origin it gives w = Σxy ÷ Σx².
Frequently asked questions
Does the power rule work for negative and fractional powers?
Yes, for any real power n. d/dx (x⁻²) = −2x⁻³ and d/dx (x^(1/3)) = ⅓x^(−2/3). For fractional powers, x usually needs to be positive.
Why is the derivative of x equal to 1?
x is x¹, so the power rule gives 1 × x⁰ = 1. On a graph, y = x is a straight line rising 1 for every 1 across: slope 1.
Is there a rule for products and quotients?
Yes: the product rule and the quotient rule, in a later lesson. For simple products, expanding the brackets and using the power rule also works.
What to learn next
- Learn the derivatives of eˣ and ln x in derivatives of exponentials and logarithms, the next lesson.
- See these derivatives drive learning in linear regression from scratch.
- Revisit where the rules come from in the derivative from first principles.