mathcalculus
derivatives
the slope at a point: how fast something changes right now.
the slope between two points of a curve is a secant. slide the second point onto the first and the secant becomes the tangent. its slope is the derivative, how fast f is changing right there.
- the secant
- (f(x + h) − f(x)) / h rise over run between two points. as h → 0 it becomes f'(x)
- power rule
- (xⁿ)' = n xⁿ⁻¹ x² has slope 2x, and x³ has 3x²
- sums and constants
- (f + g)' = f' + g' a constant has slope 0, and c·f has slope c·f'
- product rule
- (fg)' = f'g + fg' not f'·g'
- chain rule
- f(g(x))' = f'(g(x)) · g'(x) the inner slope multiplies. sin 2x has slope 2 cos 2x
- sin, eˣ, ln x
- cos x, eˣ, 1/x eˣ is its own slope
- f' = 0
- a high point, a low point, or neither x³ is flat at 0 and keeps climbing
- velocity from position, and acceleration from velocity
- finding where something is biggest or smallest
- replacing a curve by a line near a point
- gradient descent, physics, and the fade curves in noise
on this page
the idea
a straight line has one slope: rise over run, the same between any two of its points. a curve doesn’t. on the slope from to is , and from to it’s . a line through two points of a curve is a secant, and its slope is the average rate of change over that stretch.
the derivative asks a sharper question: how fast is changing at one point? slide the second point toward the first. the secant swings, its slope settles down, and in the limit the line only touches the curve: the tangent. its slope is the derivative of at that point, written or .
an animation on the graph of y = x² from x = −1.5 to 3.5 and y = −0.5 to 4.5: a line through (1, 1) and a second point (1 + h, (1 + h)²), with the run h and the rise drawn under it. h shrinks from 1 to 0.5, 0.1 and 0.01, the line swings as the second point slides in, and a table under the plot collects the slopes: 3, 2.5, 2.1, 2.01, closing in on 2. then the two points meet, the secant becomes the tangent, and its slope is 2: the derivative of x² at 1.
a derivative is a limit, the subject of the limits page. never gets to , since the quotient would read , but the slopes head somewhere, and that somewhere is .
explore
the derivative is a function of its own: a slope at every . pick a curve and drag the point. the tangent follows, and the graph of below records its slope. where is above the axis the curve climbs, where it’s below the curve falls, and where crosses zero the tangent is flat.
drag the point along the curve, or tab to it and use the arrow keys: 0.1 a step
- x
- 1
- f(x) = x²
- 1.00
- f'(x) = 2x, the slope
- 2.00
- the tangent
- y = 1 + 2(x − 1)
f' > 0: the curve climbs here, left to right
two plots stacked, with a button for each of four curves: x², x³ − 3x, sin x and eˣ. on top, the curve in cyan from x = −3 to 3, with a point to drag along it and the tangent line through the point. below, the graph of the derivative in amber over the same x, with the same x marked and its height drawn as a bar, so the slope on top is the height below. a readout gives x, f(x), f'(x), the tangent's equation, and whether the curve is climbing, falling or flat there. it opens on x² at x = 1: f(1) = 1, slope 2, tangent y = 1 + 2(x − 1), climbing. on x³ − 3x the slope is 0 at x = −1, a high point at (−1, 2), and at x = 1, a low point at (1, −2). on eˣ the two plots show the same curve. the arrow keys move the point by 0.1.
- : the slope is , a line. negative on the left, at the bottom, positive on the right
- : the slope is , which is at and . the curve turns at both, a high point at and a low one at , and falls between them
- : the slope is . it’s at , where the wave climbs fastest, and at , the crest and the trough
- : the slope is . the two plots show the same curve, and the point below sits at the height of the point above
try it
what is the derivative of x³?
pick one.
a practice exercise with four kinds of question: pick the derivative of a function like x³ or sin(2x), give the slope at a point, say where a function's slope is 0, and say whether a curve is climbing, falling or flat at a point. it opens on the derivative of x³, which is 3x², then the slope of x² at x = 3, which is 6. a slope question draws its curve with the tangent after the answer.
the rules
the definition
the slope of the secant from to , as shrinks to nothing. , and all name it. the ‘s stand for small changes: is the rise over the run of a step so short that the curve is straight along it.
constants and multiples
a constant is a flat line: is for every , so the quotient is . a multiple scales every rise by and leaves the run alone, so the slope scales by .
the power rule
expand . the first term is , the next is , and every term after that carries or more. subtract , divide by , and all that survives as is . the key idea below does it in full. the rule holds for every real , not only whole ones: has slope , and has slope .
sums
the rise of a sum is the sum of the rises, so the quotient splits in two. with the two rules above, a polynomial differentiates term by term: has slope .
the product rule
think of as the area of a rectangle with sides and . when moves by , one side grows by about and the other by . the area gains a strip along one edge and a strip along the other, plus a corner that carries and vanishes in the quotient. each factor changes while the other holds still, and the two changes add. a check: has slope , which is .
the quotient rule
is . the power rule with the chain rule below gives , and the product rule then gives . put both over . the order in the numerator matters: first, then minus .
the chain rule
move by . the inside moves by about , and sees that as its own step, so the outside moves by about times it. the rates multiply. it’s composition with slopes: runs first, then , and the slope is read inside out. is of , so its slope is . has slope .
sin and cos
the angle sum opens up as . subtract and divide by :
as , and . at they read and . so the slope is , which is where the trig page left off: at , where the wave starts out steepest. cos is sin a quarter turn ahead, so its slope is cos a quarter turn ahead: . this is in radians. in degrees, the slope of sin at 0 would be .
exponentials and logs
for any base, , so the quotient is times , a number that depends on the base and not on . at that number is for base 2 and for base 3, closing in on and . exactly one base makes it , and that base is : at its factor reads . so is its own slope, and every other is its own slope times . that is why is the natural base the exponents page promised: it grows at a rate equal to its size.
undoes : means . differentiate both sides, the left one with the chain rule: , so .
the second derivative
the slope of the slope. where the slope is increasing and the curve bends up, like a bowl. where it bends down. at a point where , that settles which kind of flat it is: bending up means a low point, bending down a high one, and means look closer. has , zero at , and : at , a high point at , and at , a low point at . has and , both at , and it is neither: the curve flattens for an instant and keeps climbing.
the noise in a shader blends with the fade curve because both its slope, , and its second derivative, , are at and at . the cubic it replaced, , has a flat slope at both ends too, but its second derivative is , which is at and at , and the bend jumped where cells met.1
motion
the slope of position is velocity: a rise in meters over a run in seconds. the slope of velocity is acceleration. a ball thrown straight up at 20 m/s, with gravity rounded to 10 m/s², is at height after seconds. then and . at it’s 15 m up and climbing at 10 m/s. at it’s at the top, 20 m, with . at it’s back at 15 m, falling at 10 m/s. the top is where the velocity crosses zero, a high point of . the integrals page runs this backwards, from velocity to distance.
linear approximation
the definition, turned around: for a small the quotient is close to , so is close to plus times . that’s the value of the tangent line at , the line the explore figure’s readout writes out. : take at , where and . then , against . , against . , against .
this is why a small enough piece of a smooth curve looks straight. the gap between the curve and its tangent is about , so it shrinks like while the piece shrinks like . on at , a step of rises against the tangent’s : a gap of , about a twentieth of the rise. a step of rises against : a gap of , about a two-hundredth. every zoom by 10 makes the curve look 10 times straighter. the series page keeps going, adding the term and the ones after it.
worked examples
a polynomial, term by term
. the power rule on each term, with the constants in front riding along and the 7 dropping out: . at the slope is , and , so the tangent there is .
a product with a chain inside
. the product rule first, with and the second factor : . the chain rule for that last slope: . so .
a quotient
, so , , and :
the slope is at : a high point at and a low one at .
where a curve turns
. , zero at and . : at , so the curve bends down there, a high point at . at , bending up, a low point at . between them and the curve falls. drag the explore figure’s point across it.
a tangent line as a calculator
: take at , where and . then . the true value is .
the key idea up close
the power rule from the limit
first. expand, subtract, divide:
the cancels, the divides out, and what’s left is , which heads to as . at that’s the movie’s .
then . the binomial theorem expands as , and every term after the second carries or more. call that tail , where is what’s left when is pulled out of it, a polynomial in :
stays finite as , so goes to , and . the point of the proof is bigger than the rule. the change is a pile of terms in , and the derivative is the coefficient of the one that’s linear in . everything with or more is lost in the quotient and the limit. that is also what the linear approximation says: .
in code
the forward difference is the secant’s slope from to . the central difference is the secant from to : the terms in its error cancel, so it’s off by about where the forward one is off by about . the run takes the slope of at , where the answer is , with from down to .
"""numerical derivatives: the forward difference (f(x + h) - f(x)) / h and the central difference (f(x + h) - f(x - h)) / (2h), with a run that shows their error as h shrinks. it falls with h, then climbs again once rounding takes over, because f(x + h) - f(x) loses digits when the two values are close. run the file to print the table for x³ at 1, where the slope is 3."""
from __future__ import annotations
from collections.abc import Callable
from typing import NamedTuple
Fn = Callable[[float], float]
def forward(f: Fn, x: float, h: float) -> float:
"""Return the slope of the secant from x to x + h: (f(x + h) - f(x)) / h.
Off by about h · f''(x) / 2, so the error shrinks like h.
"""
return (f(x + h) - f(x)) / h
def central(f: Fn, x: float, h: float) -> float:
"""Return the slope of the secant from x - h to x + h: (f(x + h) - f(x - h)) / (2h).
The h terms cancel, leaving about h² · f'''(x) / 6, so the error shrinks like h².
"""
return (f(x + h) - f(x - h)) / (2 * h)
def cube(x: float) -> float:
"""Return x³ by two multiplies, the same two in any language, so the run matches the page's chart bit for bit."""
return x * x * x
class Row(NamedTuple):
"""One step size, and how far each estimate lands from the exact slope."""
h: float
forward_error: float
central_error: float
def error_table(f: Fn, x: float, exact: float, smallest: int = 16) -> list[Row]:
"""Return a row for h = 1e-1, 1e-2, ... down to 10**-smallest, each error measured against `exact`.
Each h is parsed from its decimal spelling, so it's the same double everywhere: 10.0 ** -k would go through pow.
"""
rows = []
for k in range(1, smallest + 1):
h = float(f"1e-{k}")
rows.append(Row(h, abs(forward(f, x, h) - exact), abs(central(f, x, h) - exact)))
return rows
def best(rows: list[Row], column: str) -> Row:
"""Return the row where `column` ("forward_error" or "central_error") is smallest: where that method bottoms out."""
return min(rows, key=lambda r: getattr(r, column))
def main() -> None:
"""Print the table for x³ at 1, where the slope is 3, and where each method bottoms out."""
rows = error_table(cube, 1.0, 3.0)
print(f"{'h':>6} {'forward error':>14} {'central error':>14}")
for r in rows:
print(f"{r.h:>6.0e} {r.forward_error:>14.2e} {r.central_error:>14.2e}")
for column in ("forward_error", "central_error"):
r = best(rows, column)
print(f"{column.split('_')[0]} bottoms out at h = {r.h:.0e}, off by {getattr(r, column):.1e}")
if __name__ == "__main__":
main()the forward difference is off by at , at and at : a tenth of the error per decade, like . it bottoms out at , off by , and then the error climbs back: at , at , at , and at the quotient reads , off by the whole . the central difference is off by , then , then : a hundredth per decade, like . it bottoms out at , off by , and climbs the same way.
the climb is rounding. a double carries 53 bits, about 16 decimal digits,2 and throws most of them away: when two numbers share their first digits, their difference keeps only the rest. at the two values of agree to 8 digits, the difference has 8 left, and dividing by turns the digits that were lost into an error around . at nothing is left. the gap between and the next double up is sys.float_info.epsilon, ,3 so is , is , and so is the quotient. the best sits where the two errors meet: about for the forward difference and for the central one.
a chart of the error of two difference quotients for the slope of x³ at 1, against h from 10⁻¹ down to 10⁻¹⁶, both axes logarithmic. the forward difference, in cyan, is off by 0.31 at h = 0.1 and falls like h to 4.0 × 10⁻⁹ at h = 10⁻⁸, then climbs back as rounding takes over, to 3 at 10⁻¹⁶, where 1 + h is 1 and the quotient reads 0. the central difference, in amber, is off by 0.010 at 0.1 and falls like h² to 2.5 × 10⁻¹¹ at h = 10⁻⁶, then climbs the same way.
pitfalls
- the chain rule’s inner slope, forgotten. the slope of is , not : at the wave is twice as steep as , so its slope is . anything inside the function contributes its own slope as a factor
- isn’t . is , with slope . the product rule agrees: . the wrong rule gives , which at says for a slope that is
- the power rule needs the in the base. has slope , about , which is at . says there. and a constant like has slope , not
- no derivative at a corner or a vertical tangent. at : the secant slopes are from the right and from the left, so they settle on nothing. at : its slope grows without bound, at and at . the tangent is vertical, and a vertical line has no slope
- isn’t a high or a low point. at has slope and climbs on both sides. check the sign of on each side, or the sign of
- too small in code. the error of a difference quotient falls with only until rounding takes over, at about for the forward difference and for the central one. past that it climbs, and at the forward difference reads , because is
practice
-
differentiate , and give the slope at .
answer
term by term with the power rule: . the is a constant and drops out. at : .
-
find the slope of at , write the tangent line there, and use it to estimate .
answer
, so , and at that’s . the tangent is . at it gives , against the true .
-
differentiate , and .
answer
chain rule: . product rule: . chain rule again: .
-
a particle’s position is meters after seconds. find its velocity, the times it’s at rest, and its acceleration at those times.
answer
, which is at and : the particle stops at m and again at m. , so and m/s². at it’s being pushed back toward the start, and between the two stops it moves backwards: .
-
. where is its lowest point, and how do you know it’s the lowest?
answer
, which is at , so that’s the only flat point. : the curve bends up there, a low point. , so the lowest point is . a parabola that opens up has one low point and no high point.
-
estimate with a tangent line. then compute the forward and central differences of at with , and say why one is closer.
answer
at : and , so , against .
forward: . central: . the exact slope is . the forward quotient is , off by about , and the central one is : the terms from the two sides cancel, so only is left.
sources
-
ken perlin, improving noise, acm transactions on graphics 21(3), 2002, doi 10.1145/566654.566636 (opens in a new tab), open copy on his site (opens in a new tab): the cubic interpolant 3t² − 2t³ has the second derivative 6 − 12t, which isn’t zero at t = 0 or t = 1 and puts second order discontinuities across the faces of adjoining cells, so it’s replaced by 6t⁵ − 15t⁴ + 10t³, whose first and second derivatives are zero at both ends. ↩
-
python’s tutorial, floating-point arithmetic: issues and limitations (opens in a new tab): almost all platforms map python floats to ieee 754 binary64 doubles, which carry 53 bits of precision, and each operation’s rounding error is about 1 part in 2⁵³ at most. ↩
-
python’s sys.float_info (opens in a new tab) docs:
epsilonis the difference between 1.0 and the least float above it, c’sDBL_EPSILON, anddig, the most decimal digits a float represents faithfully, is 15. ↩