Two questions about motion
A stone is dropped from a bridge. Ignoring air resistance, after seconds it has fallen about metres. How fast is it falling at exactly ?
Speed is distance divided by time — but at a single instant no time passes and no distance is covered, so "distance ÷ time" reads . What we can compute is the average speed over a short interval from to :
Over s this is m/s; over s it is m/s. As shrinks, the averages close in on m/s. That number — the value the averages approach — is the speed at the instant .
The opposite question is just as old: a car's speedometer is recorded every moment of a journey from Accra to Kumasi. How far did the car travel? If the speed were constant, distance would be speed × time, the area of a rectangle under the speed–time graph. When the speed varies, the distance is the area under the graph — and computing areas under curves again means adding up more and more, thinner and thinner pieces.
Calculus is the mathematics of these two limits: the derivative (instantaneous rate of change) and the integral (accumulated total). Its central surprise, the fundamental theorem of calculus, is that each undoes the other.
Zooming in and slicing up
Zoom in on the graph of a smooth function, such as near the point . The more you magnify, the straighter the curve looks; under a strong enough microscope it is indistinguishable from a straight line, the tangent line. The slope of that line is the derivative: how fast changes per unit change of , right at that point.
To find an area, do the opposite: cut the region under the curve into thin vertical strips, replace each strip by a rectangle, and add up the rectangles. Thinner strips give better approximations, and the area is what these sums approach.
Both ideas rest on a single notion: the limit, the value that approximations approach as some quantity (, or the strip width) shrinks to — without ever being .
Definitions
Definition— limit (informal)
We write ("the limit of as tends to is ") if can be made as close to as we like by taking close enough to , but not equal to . The value — if it exists at all — plays no part.
The precise version ("for every there is a such that implies ") took mathematicians until the 19th century to find; it is the starting point of real analysis. In this lesson we use the following limit laws, which can be proved from that definition: if and , then , , , and provided ; also and . Consequently for every polynomial . Limits also respect inequalities: if near , then .
A function is continuous at if : the value is what the nearby values predict.
Definition— derivative
The derivative of at is
when this limit exists; then is differentiable at . The fraction is the slope of the secant line through and , and is the slope of the tangent line . The function is the derivative function , also written or .
Definition— Riemann sum and definite integral
Divide into strips of width and choose a point in the -th strip (its left end, right end or midpoint). The Riemann sum is . If these sums approach a single number as (for every way of choosing the points), that number is the definite integral . Strips where contribute negatively: the integral is a signed area. Continuous functions on always have integrals (a theorem of real analysis).
Definition— antiderivative
A function is an antiderivative of on an interval if for every in it. For example , and also , are antiderivatives of .
Worked examples
Example— Limits from tables, and limits by algebra
- A table. For (with in radians): , , . The table suggests , which is true — but a table is evidence, not proof (a table can be fooled by a function that misbehaves between the sample points).
- Algebra. : for , , so the limit is . The function is not even defined at ; the limit exists anyway.
- No limit. has no limit at (it grows without bound), and the sign function, for and for , has none either: from the left it is near , from the right near .
Example— Derivatives from the definition
For and : . So : the slope of the parabola doubles as doubles.
For and : .
The tangent line to at has slope and passes through : .
Example— Finding the turning points
Let . Then , which is at . For , (rising); for , (falling); for , again. So has a local maximum and a local minimum .
Example— An optimisation
A farmer in Malawi has m of fencing for a rectangular goat pen. With sides and , the area is for . Then at , where ; at the ends . The best pen is a square.
Explore: secants, tangents and strips
Shrink and watch the secant through and turn into the tangent. For at the table of slopes should approach — and you know exactly why, since the slope is .
From secant to tangent
The slope of the secant is exactly 2 + h. What happens as h shrinks? Then try fn = abs(x - 1).
- f(x) = x²
- secant through P and Q
- tangent line (numerical slope)
Slope of the secant PQ
(f(x₀ + h) − f(x₀)) / h = (4 − 1) / 1 = 3
Slope of the tangent at P
f′(1) ≈ 2
Numerical estimate (central difference with a tiny step).
Difference quotients as h shrinks
| h | (f(x₀ + h) − f(x₀)) / h |
|---|---|
| 1 | 3 |
| 0.1 | 2.1 |
| 0.01 | 2.01 |
| 0.001 | 2.001 |
As h shrinks, Q slides towards P, the secant turns into the tangent, and its slope settles on the derivative f′(x₀).
Now the area under from to , which we will prove is exactly . Compare left, right and midpoint sums, and watch the errors shrink as the strips multiply.
Riemann sums for the parabola
Right sums overestimate and left sums underestimate an increasing function. Which rule is most accurate?
- f(x) = x²
Right sum with 8 strips
R8 = 0.398438
Exact value of the integral
∫01 f(x) dx = 0.333333
Error (sum − integral)
0.065104
All four rules with n = 8
| Rule | Sum | Error |
|---|---|---|
| Left (L8) | 0.273438 | −0.059896 |
| Right (R8) | 0.398438 | 0.065104 |
| Midpoint (M8) | 0.332031 | −0.001302 |
| Trapezoid (T8) | 0.335938 | 0.002604 |
Double n and watch the error: left and right sums roughly halve it, midpoint and trapezoid sums cut it to about a quarter.
Finally, at : the tangent is horizontal, yet the graph keeps climbing through it.
Horizontal tangents
Move the sliders and trace along the curves to read off values.
- y = x³
- tangent to x³ at 0
- y = x³ − 3x
- y = x³: y = 1
- tangent to x³ at 0: y = 0
- y = x³ − 3x: y = −2
The rules of differentiation
Theorem— Theorem 1 (differentiable implies continuous)
If is differentiable at , then .
Proof
For , . As the first factor tends to and the second to , so by the product law the difference tends to .
∎
The converse is false: is continuous at , but its difference quotient is for and for , so it has no limit. A graph with a corner has no tangent there.
Theorem— Theorem 2 (sums and constant multiples)
If and are differentiable at and is a constant, then and .
Proof
The difference quotient of is the sum of the difference quotients of and , and that of is times that of ; apply the limit laws.
∎
Theorem— Theorem 3 (product rule)
If and are differentiable at , then .
Proof
Add and subtract :
As : by Theorem 1, and the two quotients tend to and . By the limit laws the whole expression tends to .
∎
Theorem— Theorem 4 (power rule)
For every integer : .
Proof
Induction on . For , the difference quotient of is , so the derivative is . Suppose . Writing , the product rule gives
∎
With Theorem 2, every polynomial can now be differentiated term by term: . (The constant has derivative : its difference quotient is .)
Theorem— Theorem 5 (Fermat's theorem on interior extrema)
Suppose is defined on an open interval containing , has a local maximum or minimum at , and is differentiable at . Then .
Proof
Take a local maximum: for all small . For small the difference quotient has numerator and denominator , so it is ; since limits respect inequalities, . For small the numerator is and the denominator , so the quotient is , giving . Hence . For a minimum, apply this to .
∎
The converse is false. For , , but is neither a maximum nor a minimum: for every and , however small is. A zero derivative only marks a candidate; to decide, look at the sign of on each side (as in the worked example) or compare values.
Area under a parabola, and the fundamental theorem
Archimedes found the area of a parabolic segment more than 2,200 years ago. Here is the modern version of that result, by Riemann sums.
Theorem— Lemma 6 (sum of squares)
For every : .
Proof
Induction on . For both sides are . If the formula holds for , then
which is the formula for , because .
∎
Theorem— Theorem 7 (the area under y = x² on [0, 1] is 1/3)
The right and left Riemann sums of on with strips are
and both tend to as . Hence .
Proof
The -th strip is , of width . Using right endpoints and Lemma 6,
With left endpoints we get in the same way. Dividing top and bottom by ,
Since is increasing on , every Riemann sum with strips lies between and (each strip's height lies between the heights at its two ends), so every Riemann sum tends to .
∎
Computing every area this way would be exhausting. The fundamental theorem gives a shortcut.
Theorem— Fundamental theorem of calculus
If is continuous on and is an antiderivative of there, then
We give the idea rather than a complete proof (which belongs to real analysis). Let be the area accumulated from up to . Increasing by a small adds a thin strip of width and height about , so , and dividing by suggests — making this precise uses the continuity of . So and have the same derivative, and two functions with the same derivative on an interval differ by a constant (a consequence of the mean value theorem). Hence ; putting gives , and putting gives .
Example— Integrals by antiderivatives
- , matching Theorem 7 — two very different routes to the same number.
- .
- , but : the area below the axis on counts negatively and cancels the area above.
Calculus in Lean
Mathlib states that has derivative at as HasDerivAt f f' a, and writes limits with filters: Tendsto g (𝓝[≠] 0) (𝓝 L) says " as with ". First the derivative of straight from the definition, in three steps that mirror the human computation:
/-- **The difference quotient of `x²`.** For `h ≠ 0`,
`((a + h)² − a²)/h = (2ah + h²)/h = 2a + h`. -/
theorem diff_quotient_sq (a h : ℝ) (hh : h ≠ 0) : ((a + h) ^ 2 - a ^ 2) / h = 2 * a + h := by
field_simp
ring/-- **Its limit is `2a`.** As `h → 0` with `h ≠ 0`, the quotient equals `2a + h`, and
`2a + h → 2a`. The value at `h = 0` itself is never used. -/
theorem tendsto_diff_quotient_sq (a : ℝ) :
Tendsto (fun h => ((a + h) ^ 2 - a ^ 2) / h) (𝓝[≠] 0) (𝓝 (2 * a)) := by
have hlin : Tendsto (fun h : ℝ => 2 * a + h) (𝓝[≠] 0) (𝓝 (2 * a)) := by
have : Tendsto (fun h : ℝ => 2 * a + h) (𝓝 0) (𝓝 (2 * a + 0)) :=
tendsto_const_nhds.add tendsto_id
rw [add_zero] at this
exact tendsto_nhdsWithin_of_tendsto_nhds this
refine tendsto_nhdsWithin_congr (fun h hh => ?_) hlin
exact (diff_quotient_sq a h hh).symm/-- **`(x²)′ = 2a` at every point `a`**, from the limit definition: Mathlib's `HasDerivAt` is
equivalent (`hasDerivAt_iff_tendsto_slope_zero`) to the difference quotients tending to the
derivative, and we computed that limit above. -/
theorem hasDerivAt_sq (a : ℝ) : HasDerivAt (fun x : ℝ => x ^ 2) (2 * a) a := by
rw [hasDerivAt_iff_tendsto_slope_zero]
refine (tendsto_diff_quotient_sq a).congr (fun t => ?_)
simp [smul_eq_mul, div_eq_inv_mul]The power rule, by induction with Mathlib's product rule HasDerivAt.mul — the proof of Theorem 4 — and Mathlib's own version:
/-- **The power rule** `(xⁿ⁺¹)′ = (n + 1) xⁿ`, by induction on `n`.
For `n = 0`, `(x¹)′ = 1`. For the step write `x^(n+2) = x^(n+1) · x` and use the product rule
`(uv)′ = u′v + uv′`: the derivative is `(n + 1)xⁿ · x + x^(n+1) · 1 = (n + 2) x^(n+1)`.
(We write the exponent as `n + 1` so that the rule never needs `n − 1`.) -/
theorem power_rule (n : ℕ) (x : ℝ) :
HasDerivAt (fun y : ℝ => y ^ (n + 1)) ((n + 1) * x ^ n) x := by
induction n with
| zero => simpa using hasDerivAt_id' x
| succ k ih =>
have h := ih.mul (hasDerivAt_id x)
have hf : (fun y : ℝ => y ^ (k + 1 + 1)) = (fun y : ℝ => y ^ (k + 1)) * id := by
funext y
simp [pow_succ]
rw [hf]
convert h using 1
push_cast
simp only [id]
ring/-- The power rule from Mathlib, `hasDerivAt_pow`: `(xⁿ)′ = n xⁿ⁻¹` (with natural-number
subtraction, so for `n = 0` it reads `(x⁰)′ = 0 · x^0 = 0`, which is still correct). -/
theorem power_rule_library (n : ℕ) (x : ℝ) :
HasDerivAt (fun y : ℝ => y ^ n) (n * x ^ (n - 1)) x :=
hasDerivAt_pow n xFermat's theorem from Mathlib, and the counterexample to its converse, proved here:
/-- **Fermat's theorem on interior extrema:** if `f` has a local maximum or minimum at `a` and is
differentiable there, then `f′(a) = 0`. This applies Mathlib's
`IsLocalExtr.hasDerivAt_eq_zero`. -/
theorem fermat {f : ℝ → ℝ} {a f' : ℝ} (hext : IsLocalExtr f a) (hd : HasDerivAt f f' a) :
f' = 0 :=
hext.hasDerivAt_eq_zero hd/-- `x³` has derivative `3 · 0² = 0` at `0` (the power rule with `n = 2`). -/
theorem cube_deriv_zero : HasDerivAt (fun x : ℝ => x ^ 3) 0 0 := by
have h := power_rule 2 0
norm_num at h
exact h/-- **The converse of Fermat's theorem is false.** `x³` has `f′(0) = 0`, but `0` is neither a
local maximum nor a local minimum: however small an interval around `0` we take, it contains a
point `t > 0` with `t³ > 0 = f(0)` and the point `−t` with `(−t)³ < 0`. -/
theorem cube_not_extremum : ¬ IsLocalExtr (fun x : ℝ => x ^ 3) 0 := by
rintro (hmin | hmax)
· -- A local minimum would need `x³ ≥ 0` near `0`; `x = −ε/2` breaks it.
obtain ⟨ε, hε, h⟩ := Metric.eventually_nhds_iff.mp hmin
have hd : dist (-(ε / 2)) 0 < ε := by
rw [Real.dist_eq, sub_zero, abs_neg, abs_of_pos (by linarith)]
linarith
have := h hd
simp only at this
nlinarith [pow_pos (half_pos hε) 3]
· -- A local maximum would need `x³ ≤ 0` near `0`; `x = ε/2` breaks it.
obtain ⟨ε, hε, h⟩ := Metric.eventually_nhds_iff.mp hmax
have hd : dist (ε / 2) 0 < ε := by
rw [Real.dist_eq, sub_zero, abs_of_pos (by linarith)]
linarith
have := h hd
simp only at this
nlinarith [pow_pos (half_pos hε) 3]/-- **The limit at a point need not be the value there.** `f(x) = (x² − 1)/(x − 1)` tends to `2`
as `x → 1`, because `f(x) = x + 1` for `x ≠ 1`. At `x = 1` the formula reads `0/0`, which is
meaningless on paper; Lean's convention `0/0 = 0` gives `f(1) = 0` — a value that has nothing to
do with the limit `2`. -/
theorem limit_not_value :
Tendsto (fun x : ℝ => (x ^ 2 - 1) / (x - 1)) (𝓝[≠] 1) (𝓝 2) ∧
(fun x : ℝ => (x ^ 2 - 1) / (x - 1)) 1 = 0 := by
constructor
· have hlin : Tendsto (fun x : ℝ => x + 1) (𝓝[≠] 1) (𝓝 2) := by
have : Tendsto (fun x : ℝ => x + 1) (𝓝 1) (𝓝 (1 + 1)) :=
tendsto_id.add tendsto_const_nhds
norm_num at this
exact tendsto_nhdsWithin_of_tendsto_nhds this
refine tendsto_nhdsWithin_congr (fun x hx => ?_) hlin
have hx1 : x - 1 ≠ 0 := sub_ne_zero.mpr hx
field_simp
ring
· norm_numTheorem 7, with the right Riemann sums as a Lean definition:
/-- `0² + 1² + ⋯ + n² = n(n + 1)(2n + 1)/6`, by induction on `n`. -/
theorem sum_squares (n : ℕ) :
∑ k ∈ range (n + 1), (k : ℝ) ^ 2 = n * (n + 1) * (2 * n + 1) / 6 := by
induction n with
| zero => simp
| succ m ih =>
rw [sum_range_succ, ih]
push_cast
ring/-- The **right Riemann sum** of `f(x) = x²` on `[0, 1]` with `n` strips of width `1/n`: the
strip over `[k/n, (k + 1)/n]` has height `f((k + 1)/n)`. -/
noncomputable def rightSum (n : ℕ) : ℝ :=
∑ k ∈ range n, (((k : ℝ) + 1) / n) ^ 2 * (1 / n)/-- **A closed form for the Riemann sum:** for `n ≥ 1`,
`rightSum n = (1² + 2² + ⋯ + n²)/n³ = (n + 1)(2n + 1)/(6n²)`. -/
theorem rightSum_formula (n : ℕ) (hn : n ≠ 0) :
rightSum n = ((n : ℝ) + 1) * (2 * n + 1) / (6 * (n : ℝ) ^ 2) := by
have hn' : (n : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hn
have key : ∑ k ∈ range n, ((k : ℝ) + 1) ^ 2 = (n : ℝ) * (n + 1) * (2 * n + 1) / 6 := by
have h := sum_squares n
rw [sum_range_succ'] at h
simpa using h
have hsum : rightSum n = (∑ k ∈ range n, ((k : ℝ) + 1) ^ 2) / (n : ℝ) ^ 3 := by
rw [rightSum, sum_div]
refine sum_congr rfl (fun k _ => ?_)
field_simp
rw [hsum, key]
field_simp/-- **The Riemann sums converge to `1/3`.** For `n ≥ 1`,
`(n + 1)(2n + 1)/(6n²) = (1 + 1/n)(2 + 1/n)/6`, and `1/n → 0`, so the limit is
`(1 · 2)/6 = 1/3`: the area under `y = x²` from `0` to `1`. -/
theorem rightSum_tendsto : Tendsto rightSum atTop (𝓝 (1 / 3)) := by
have hlim : Tendsto (fun n : ℕ => (1 + 1 / (n : ℝ)) * (2 + 1 / (n : ℝ)) / 6) atTop
(𝓝 ((1 + 0) * (2 + 0) / 6)) :=
((tendsto_const_nhds.add tendsto_one_div_atTop_nhds_zero_nat).mul
(tendsto_const_nhds.add tendsto_one_div_atTop_nhds_zero_nat)).div_const 6
norm_num at hlim
refine hlim.congr' ?_
filter_upwards [eventually_ne_atTop 0] with n hn
have hn' : (n : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hn
rw [rightSum_formula n hn]
field_simpMathlib's integral is not defined by Riemann sums but by a more general construction (the Lebesgue, or Bochner, integral), which agrees with the Riemann integral for continuous functions. We did not formalise that agreement for this example; instead we compute the integral with Mathlib's fundamental theorem of calculus and with its table of integrals:
/-- **The fundamental theorem in action:** `∫₀² x² dx = 8/3`. Since `F(x) = x³/3` has
`F′(x) = x²`, the integral is `F(2) − F(0) = 8/3`. This applies Mathlib's fundamental theorem
`intervalIntegral.integral_eq_sub_of_hasDerivAt`. -/
theorem ftc_square : ∫ x in (0 : ℝ)..2, x ^ 2 = 8 / 3 := by
have hF : ∀ x ∈ Set.uIcc (0 : ℝ) 2, HasDerivAt (fun y : ℝ => y ^ 3 / 3) (x ^ 2) x := by
intro x _
have h := (hasDerivAt_pow 3 x).div_const 3
convert h using 1
norm_num
have hint : IntervalIntegrable (fun x : ℝ => x ^ 2) MeasureTheory.volume 0 2 :=
(continuous_pow 2).intervalIntegrable 0 2
rw [intervalIntegral.integral_eq_sub_of_hasDerivAt hF hint]
norm_num/-- `∫₀¹ x² dx = 1/3`, the limit of the Riemann sums above, from Mathlib's `integral_pow`. -/
theorem integral_sq_unit : ∫ x in (0 : ℝ)..1, x ^ 2 = 1 / 3 := by
rw [integral_pow]
norm_num/-- **Integrals are signed.** `∫₀^{2π} sin x dx = cos 0 − cos 2π = 0`: the area above the axis
on `[0, π]` cancels the area below it on `[π, 2π]`. This applies Mathlib's `integral_sin`. -/
theorem integral_sin_signed : ∫ x in (0 : ℝ)..(2 * Real.pi), Real.sin x = 0 := by
rw [integral_sin]
simpExact, numerical and symbolic calculus
"""Derivatives as limits of difference quotients - and the limits of floats.
For f(x) = x^2 the difference quotient ((a + h)^2 - a^2)/h equals 2a + h
exactly (checked with fractions), so it tends to 2a. For f = sin at a = 1 the
quotient tends to cos 1, but in floating point the error first shrinks like h
(the mathematics) and then grows again like 1e-16/h (rounding: subtracting two
nearly equal numbers). SymPy computes the limit and the power rule exactly.
"""
import math
from fractions import Fraction
import sympy
def forward_quotient(f, a, h):
"""(f(a + h) - f(a)) / h, the slope of a secant line."""
if h == 0:
raise ValueError("h must be non-zero")
return (f(a + h) - f(a)) / h
def central_quotient(f, a, h):
"""(f(a + h) - f(a - h)) / (2h), a symmetric secant slope."""
if h == 0:
raise ValueError("h must be non-zero")
return (f(a + h) - f(a - h)) / (2 * h)
def square(x):
"""f(x) = x^2."""
return x * x
def quotient_errors(exponents):
"""Rows (h, forward error, central error) for sin at 1 against cos 1."""
exact = math.cos(1.0)
rows = []
for k in exponents:
h = 10.0 ** (-k)
fwd = abs(forward_quotient(math.sin, 1.0, h) - exact)
cen = abs(central_quotient(math.sin, 1.0, h) - exact)
rows.append((h, fwd, cen))
return rows
def symbolic_results():
"""SymPy's limit of the sine quotient and derivative of x^n."""
x, h = sympy.symbols("x h")
n = sympy.symbols("n", positive=True, integer=True)
lim = sympy.limit((sympy.sin(1 + h) - sympy.sin(1)) / h, h, 0)
deriv = sympy.simplify(sympy.diff(x ** n, x))
return lim, deriv
def main():
print("Exact fractions: ((a + h)^2 - a^2)/h for a = 3")
for h in [Fraction(1, 10), Fraction(1, 1000), Fraction(-1, 10 ** 6)]:
q = forward_quotient(square, Fraction(3), h)
print(f" h = {str(h):>10}: quotient = {q} (= 2a + h)")
print()
print("Floats: sin at a = 1, compared with cos 1")
print(" h forward error central error")
for h, fwd, cen in quotient_errors(range(1, 14, 2)):
print(f" {h:8.0e} {fwd:.2e} {cen:.2e}")
print("The forward error falls like h, the central one like h^2, until")
print("rounding (about 1e-16 / h) takes over for tiny h.")
print()
lim, deriv = symbolic_results()
print(f"SymPy: limit of (sin(1 + h) - sin 1)/h as h -> 0 is {lim}")
print(f"SymPy: d/dx x^n = {deriv}")
print()
print("Epistemic status: the fraction rows are exact; the float table is")
print("numerical evidence affected by rounding, so it can suggest but")
print("never prove a limit; the SymPy results are symbolic computations.")
print("The lesson's proofs establish the derivatives for every a and n.")
if __name__ == "__main__":
main()The float table holds a lesson. Making smaller first improves the estimate of , as the mathematics predicts; but below about the error grows again. The computer stores and with about 16 significant digits, and subtracting two nearly equal numbers wipes out most of them. A limit is an idea about exact numbers; numerical methods must balance the two kinds of error (see Numerical methods).
"""Riemann sums for the area under y = x^2, computed exactly.
With fractions there is no rounding at all: the right Riemann sum of x^2 on
[0, 1] with n strips is exactly (n + 1)(2n + 1)/(6n^2), its error is exactly
1/(2n) + 1/(6n^2), and the midpoint sum misses 1/3 by exactly 1/(12n^2). The
fundamental theorem (via SymPy) gives the limit 1/3 at once. A last check
shows that integrals are signed: midpoint sums of sin on [0, 2 pi] tend to 0.
"""
import math
from fractions import Fraction
import sympy
def riemann_sum(f, a, b, n, rule="right"):
"""Sum of n strips of width (b - a)/n; heights at the left end, right
end or midpoint of each strip. Exact when f, a, b are rational."""
if n < 1:
raise ValueError("n must be at least 1")
offset = {"left": Fraction(0), "right": Fraction(1), "midpoint": Fraction(1, 2)}
if rule not in offset:
raise ValueError("rule must be left, right or midpoint")
width = (b - a) / n
return sum(f(a + (k + offset[rule]) * width) for k in range(n)) * width
def square(x):
"""f(x) = x^2."""
return x * x
def right_closed_form(n):
"""(n + 1)(2n + 1) / (6 n^2), the right sum of x^2 on [0, 1]."""
return Fraction((n + 1) * (2 * n + 1), 6 * n * n)
def antiderivative_check():
"""SymPy: an antiderivative of x^2 and the integral over [0, 1]."""
x = sympy.symbols("x")
return sympy.integrate(x ** 2, x), sympy.integrate(x ** 2, (x, 0, 1))
def main():
zero, one = Fraction(0), Fraction(1)
third = Fraction(1, 3)
agree = all(
riemann_sum(square, zero, one, n) == right_closed_form(n)
for n in range(1, 201)
)
print(f"Right sum = (n+1)(2n+1)/(6n^2) exactly for n = 1..200: {agree}")
print()
print(" n left sum right sum midpoint right - 1/3")
for n in [1, 2, 4, 10, 100]:
left = riemann_sum(square, zero, one, n, "left")
right = riemann_sum(square, zero, one, n, "right")
mid = riemann_sum(square, zero, one, n, "midpoint")
print(f"{n:4d} {float(left):.8f} {float(right):.8f} "
f"{float(mid):.8f} {str(right - third)}")
n = 100
err_right = riemann_sum(square, zero, one, n) - third
err_mid = riemann_sum(square, zero, one, n, "midpoint") - third
print(f"n = 100: right error = 1/(2n) + 1/(6n^2)? "
f"{err_right == Fraction(1, 2 * n) + Fraction(1, 6 * n * n)}")
print(f"n = 100: midpoint error = -1/(12n^2)? "
f"{err_mid == Fraction(-1, 12 * n * n)}")
print()
anti, area = antiderivative_check()
print(f"SymPy: antiderivative {anti}, so the area is F(1) - F(0) = {area}")
print()
signed = riemann_sum(math.sin, 0.0, 2 * math.pi, 1000, "midpoint")
above = riemann_sum(math.sin, 0.0, math.pi, 1000, "midpoint")
print(f"sin on [0, 2pi], 1000 strips: |midpoint sum| < 1e-12? "
f"{abs(signed) < 1e-12}")
print(f"Signed area cancels: the part above the axis alone is {above:.6f}")
print("(the exact value of that part is 2).")
print()
print("Epistemic status: the fraction sums are exact and the closed form")
print("is checked for n = 1..200 only (the lesson proves it for all n);")
print("SymPy's integral is symbolic; the sine sums are floating point.")
if __name__ == "__main__":
main()With fractions there is no rounding at all, and the experiment confirms the closed form of Theorem 7 for every up to — evidence for those cases, while the induction proves it for all . It also measures the errors exactly: the right sum is off by , the midpoint sum by only .
Exercises
1. Introductory calculus
Warm-upHumanFind .
2. Introductory calculus
Warm-upHumanLet . Compute .
3. Introductory calculus
CoreHumanThe tangent line to at has equation . Find .
4. Introductory calculus
CoreHumanFor , which statement is correct?
5. Introductory calculus
CoreHumanWhich function is a counterexample to the claim "if then has a local maximum or minimum at "?
6. Introductory calculus
CoreHumanCompute .
7. Introductory calculus
StretchHumanIn the proof of Fermat's theorem, has a local maximum at . Why is for small negative ?
8. Introductory calculus
CoreFormalIn Lean, with f := fun x : ℝ => (x ^ 2 - 1) / (x - 1), the lesson proves both Tendsto f (𝓝[≠] 1) (𝓝 2) and f 1 = 0. What is the right conclusion?
9. Introductory calculus
StretchComputationalWrite right_sum(f, a, b, n) returning the right Riemann sum . Use Fraction so that the sums are exact when a, b are fractions and f is a polynomial. Then check Theorem 7: for on it should equal .
Common misconceptions
Misconception
"If , then has a maximum or minimum at ." Fermat's theorem only goes one way. has and no extremum at . Conversely, an extremum can occur where does not exist ( at ) or at an endpoint of the interval.
Misconception
"The limit at a point is the value there." Only for continuous functions. has limit at but no value there; a function that is everywhere except has limit at but value . The definition of explicitly ignores .
Misconception
"An integral always gives a (positive) area." Integrals are signed: . To get the total geometric area between a graph and the axis, integrate — in practice, split the interval where changes sign.
Misconception
"To find the derivative, put in the difference quotient." At the quotient is , which is meaningless. You must first simplify for (as in ) and then take the limit.
Misconception
"." The exponent comes down as a factor: . Check with : the slope at is , not .
Other ways of seeing
Geometry— The best straight-line approximation
The derivative is the slope of the line that fits the graph best near : , where the error is small compared with (). For , exactly. This "linearisation" view is the one that generalises: in several variables the derivative becomes a linear map (a matrix), and on curved spaces it becomes a map between tangent planes. See Multivariable and vector calculus.
Physics— Velocity, acceleration and Newton
Newton invented his "method of fluxions" to describe motion: velocity is the derivative of position, acceleration the derivative of velocity, and his second law says force determines the second derivative of position. For the falling stone, gives and m/s², the constant acceleration due to gravity near the Earth's surface. Reading the integral backwards, the distance travelled is the area under the velocity graph: m in the first two seconds. (The model ignores air resistance — physics, not mathematics, decides when that is acceptable.)
Analysis— Making 'close' precise
Newton and Leibniz could compute brilliantly but could not say exactly what a limit is; Bishop Berkeley mocked their vanishing increments as "ghosts of departed quantities". Cauchy (1821) and Weierstrass made it precise with inequalities ( and ), and the subject became rigorous enough to handle shocks: Weierstrass (1872) published a function that is continuous everywhere and differentiable nowhere, and the theorems quoted here — limit laws, the integrability of continuous functions, the mean value theorem — all rest on the completeness of the real numbers (see Real numbers).
Computation— When there is no formula
Most integrals cannot be written with familiar functions — is a famous example — so they are computed numerically. The midpoint and trapezoid rules have errors proportional to for smooth functions, and Simpson's rule to ; derivatives are estimated by difference quotients whose step must balance truncation error against rounding error, as the experiment shows. See Numerical methods.
Wonder Trails
Optional, and never graded: a question that leads somewhere further.
Wonder Trail · Optional · never gradedHow sharply does a road bend?Driving along a winding road, how sharply does it bend at each point? Is there a circle that fits the road best at each point — and what is its radius?Follow the trailHistory and global context
- Ancient areas and volumes. Archimedes (3rd century BCE) proved in Quadrature of the Parabola that a parabolic segment has the area of an inscribed triangle, by the "method of exhaustion". In China, Liu Hui (3rd century CE) approximated the circle by polygons with ever more sides, and Zu Chongzhi and his son Zu Geng (5th–6th centuries) found the volume of a sphere using a principle of comparing cross-sections later rediscovered by Cavalieri.
- Medieval advances. Ibn al-Haytham (about 1000 CE, in Cairo) found formulas for sums of fourth powers and used them to compute the volume of a solid of revolution of a parabola. In Kerala, Mādhava of Saṅgamagrāma (14th century) and his school found infinite series for sine, cosine and the arctangent, centuries before they appeared in Europe.
- The invention of calculus. Pierre de Fermat (1630s) found tangents and maxima with methods close to our difference quotients. Isaac Newton (from the 1660s) and Gottfried Wilhelm Leibniz (published from 1684) independently created calculus and recognised the fundamental theorem; Leibniz's notations and are still used. A bitter priority dispute followed. Maria Gaetana Agnesi's Instituzioni analitiche (1748) was one of the first comprehensive calculus textbooks and was widely translated.
- Rigour. Augustin-Louis Cauchy (1821) based calculus on limits, Bernhard Riemann (1854) defined the integral by the sums named after him, and Karl Weierstrass gave limits their – form.
Further reading
- Silvanus P. Thompson, Calculus Made Easy (1910) — still a friendly first read ("what one fool can do, another can").
- Gilbert Strang, Calculus (1991) — a complete course with many applications.
- Michael Spivak, Calculus (1967) — the rigorous next step, proving everything this lesson states.
- Tom M. Apostol, Calculus, Volume 1 (1961) — integration before differentiation, as in history.
- C. H. Edwards, The Historical Development of the Calculus (1979).