123451015200xy = x²h = 1h = 0.1h = 0.01h → 01def f(x): return x**22def slope(x, h):3 return (f(x+h)-f(x))/h4slope(3, 0.001)5x = 3 - 0.25 * 2*317QP
Graph board: the curve y = x², with P (pink) and Q (amber) on itSecant (orange) through P and Q; tangent (green) at PSlopes table and calculator: each secant slope, then the limitPython card: estimate the slope with a small h, then one descent stepThe curve y = x² on an upright board. P stays at (3, 9) while Q sits a step h to its right; the secant through them turns as h shrinks, and its slopes, 7, 6.1 and 6.01, fill the table until the limit, 6, is the slope of the tangent at P. Then P slides along the curve with its tangent (slopes 2, 4 and 6 at x = 1, 2 and 3: f′(x) = 2x), and gradient descent rolls it downhill: 3, 1.5, 0.75, 0.375. A forward difference has two errors that pull in opposite ways: a large h is off by about h (here exactly h, since the slope is 6 + h), and a tiny h loses digits when two almost equal numbers are subtracted. For a float near 1, an h around 10⁻⁸ is a common compromise.

Secant slopes

  1. 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?

The limit

In code

Machine learning

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).