Secant slopes
A derivative measures how fast a function's output changes as its input changes, at one exact point. A straight line has one slope everywhere: rise ÷ run. The curve f(x) = x² gets steeper as x grows. How steep is it at x = 3?
Take a second point Q a step h to the right of P. With h = 1, Q is (4, 16). The straight line through P and Q is called a secant. Its slope is rise ÷ run: (16 − 9) ÷ 1 = 7.
Now shrink h. With h = 0.1, Q is (3.1, 9.61) and the slope is 0.61 ÷ 0.1 = 6.1. With h = 0.01 it is 6.01. As Q slides toward P, the secant turns and its slope closes in on 6.
The limit
Expand: (3 + h)² − 9 = 6h + h². Divide by h, and the secant's slope is exactly 6 + h for every h that is not 0. So as h shrinks toward 0, the slope gets as close to 6 as we like.
That target is called a limit. The derivative is f′(x) = lim (f(x + h) − f(x)) ÷ h as h → 0. Here f′(3) = 6. The line through P with slope 6 is the tangent: it touches the curve at P.
At any x the same algebra gives (x + h)² − x² = 2xh + h², so f′(x) = 2x. Slide P along the curve: the tangent's slope is 2, 4, then 6 at x = 1, 2, 3. In general, xⁿ has derivative n·xⁿ⁻¹.
In code
A program can estimate a derivative with a small h: slope(x, h) returns (f(x + h) − f(x)) ÷ h. At x = 3 with h = 0.001 it gives 6.000999999999479. That is 6 + h, give or take a tiny rounding error.
A tinier h does not always help. A Python float keeps about 16 significant digits (the digits that carry real information). The same slope() with h = 10⁻⁸ gives 5.99999996, with 10⁻¹⁵ 5.33, and with 10⁻¹⁶, 3 + h rounds to 3: slope 0.0.
Machine learning
Machine learning uses derivatives to shrink an error. Gradient descent steps against the slope, with a step size (learning rate) of 0.25: x ← x − 0.25 · f′(x). From x = 3: 3 − 0.25 × 6 = 1.5, then 0.75, then 0.375.
Try it in the Python prompt
;; step 1/9 · How steep is a curve? >>> def f(x): return x**2 ... >>> f(3) 9 >>> [f(x) for x in range(5)] [0, 1, 4, 9, 16]
f′(x) (read 'f prime of x') and dy/dx are two ways to write the same derivative. The derivative of x² is 2x, so the slope of y = x² at x = 3 is 6. The slopes 6.1 and 6.01 are exact maths. Python prints 6.100000000000012 and 6.009999999999849, because 0.1 and 0.01 have no exact binary form and each float keeps 53 binary digits (about 16 decimal digits).