Limits and secant lines
The slope of a curve at a single point is hard to measure. Instead, we approximate it with the slope of a line through two nearby points. This is called a secant line.
Given a function f and a point x, pick a small number h and compute the slope between (x, f(x)) and (x + h, f(x + h)):
slope ≈ (f(x + h) - f(x)) / h
As h gets closer to 0, the secant line becomes a better estimate of the tangent line. The exact derivative is the limit of this ratio as h → 0.
Approximating a derivative
We cannot set h = 0 in code because we would divide by zero. But we can choose a very small h, like 0.0001. That gives a good numerical approximation of the derivative.
For example, if f(x) = x², we expect f'(x) = 2x. At x = 3, the exact derivative is 6. With h = 0.0001, the code gives something very close to 6.
Key idea: A derivative is the limit of a slope ratio. Code can approximate it by using a tiny but non-zero h.
Approximating an integral
The integral of a function is the area under its curve. To approximate it, split the area into thin rectangles, add up their areas, and let the rectangles get thinner.
- Pick an interval [a, b] and a number of rectangles n.
- Each rectangle has width Δx = (b - a) / n.
- The height of each rectangle is f(x) at some x inside that slice.
- The total area is approximately Σ f(xᵢ) Δx.
This is a Riemann sum. As n gets larger, the estimate gets closer to the true integral.
Interactive slope and area
We will use f(x) = x² on the interval [0, 2]. Adjust x for the derivative and n for the number of rectangles. Watch the secant line and the rectangles update.
Calculus in Python
Here are numerical functions for derivatives and integrals. They are not magic; they just repeat the steps above with tiny numbers.
def derivative(f, x, h=0.0001): # slope of secant line through x and x + h return (f(x + h) - f(x)) / h def integral(f, a, b, n=1000): # Riemann sum with n rectangles dx = (b - a) / n total = 0 for i in range(n): x = a + i * dx total += f(x) * dx return total def f(x): return x**2 print(derivative(f, 3)) # ≈ 6 print(integral(f, 0, 2, 1000)) # ≈ 2.667
6.000100000001296 2.666666666999924
The derivative approximation is not exact, but it is close. The integral approximation is even closer when n is large. This is the numerical heart of calculus: use tiny steps to approach exact answers.
Quick quiz
1. What does a derivative measure?
2. Why can't we use h = 0 in the derivative approximation?
3. What does a Riemann sum approximate?
Keep learning
You have used code for algebra, geometry, trigonometry, and calculus. Next, explore how code handles data with statistics.
Part of the “Coding for High School Math” series.