Card 1 / 3
The derivative is the slope of at . Estimate it with the central difference: evaluate a tiny step on each side of and take the slope between the two points.
f |
x |
h |
result | exact |
|---|---|---|---|---|
3 |
1e-5 |
6.000 |
||
0 |
1e-5 |
1.000 |
||
1 |
1e-5 |
2.718 |
||
1 |
0.5 |
3.250 |
(a coarse shows the error) | |
| constant | 2 |
1e-5 |
0 |
Why the symmetric form: the one-sided has an error proportional to , while the central form cancels the even-order terms and its error is proportional to . Keep small but not tiny: below about the subtraction loses its leading digits to rounding. This estimate is the yardstick that gradient checking later compares analytic gradients against.
def derivative(f, x: float, h: float = 1e-5) -> float:
"""Central-difference estimate of f'(x): (f(x + h) - f(x - h)) / (2h).
f: a function float -> float
x: the point at which to estimate the slope
h: half-width of the step (default 1e-5)
Returns a float.
"""
return (f(x + h) - f(x - h)) / (2 * h)Card 2 / 3
For a scalar function of several inputs, the gradient is the vector of partial derivatives, one per coordinate. Estimate each one by nudging only that coordinate: