Calculus in Depth Exercises
Ten exercises that run across the whole course: precise limits, Newton's method, Simpson's rule, a logistic model, polar area, series error bounds, curvature, Lagrange multipliers, a Monte Carlo triple integral and the fundamental theorem for line integrals. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Every exercise has an exact answer you can find on paper. Work it out first, then let the code confirm it. When the two disagree, one of them has a bug, and finding out which is the real exercise.
| # | Exercise | Practises |
|---|---|---|
| 1 | Find a for an | the precise definition of a limit |
| 2 | Where | Newton's method |
| 3 | Simpson's rule for | approximate integration |
| 4 | A logistic population by Euler | population models, Euler's method |
| 5 | The area of a cardioid | areas in polar coordinates |
| 6 | How many terms for ? | alternating series |
| 7 | Curvature of a helix | arc length and curvature |
| 8 | The biggest box under a plane | Lagrange multipliers |
| 9 | Two crossing cylinders | triple integrals, Monte Carlo |
| 10 | Work done by a gradient field | the fundamental theorem for line integrals |
Exercise 1: Find a for an
For as and , find the largest such that guarantees . The condition means (for near 3), so is the smaller distance from 3 to the ends of that interval. The starter leaves both ends at 3, which gives , and the grid check passes trivially because every test point is 3.
import math
eps, a = 0.01, 3
left = a # TODO: left end of the interval where |x^2 - 9| < eps
right = a # TODO: right end
delta = min(a - left, right - a)
print(f"delta = {delta:.7f}")
xs = [a - delta + 2 * delta * k / 10000 for k in range(1, 10000)]
print("all inside:", all(abs(x * x - 9) < eps for x in xs))delta = 0.0000000
all inside: True
Expected output when solved:
delta = 0.0016662
all inside: TrueHint: The right end is closer to 3, because grows faster to the right of 3 than it falls to the left. Compare with the rough rule .
Show solution
import math
eps, a = 0.01, 3
left = math.sqrt(9 - eps)
right = math.sqrt(9 + eps)
delta = min(a - left, right - a)
print(f"delta = {delta:.7f}")
xs = [a - delta + 2 * delta * k / 10000 for k in range(1, 10000)]
print("all inside:", all(abs(x * x - 9) < eps for x in xs))delta = 0.0016662
all inside: True
, slightly less than .
Exercise 2: Where
Solve with Newton's method, for , starting at . The starter's derivative is a placeholder 0.
import math
f = lambda x: math.cos(x) - x
df = lambda x: 0.0 # TODO: the derivative of cos(x) - x
x = 1.0
for i in range(5):
if df(x) == 0:
print("f'(x) = 0, cannot take a Newton step")
break
x = x - f(x) / df(x)
print(i + 1, f"{x:.12f}")f'(x) = 0, cannot take a Newton step
Expected output when solved:
1 0.750363867840
2 0.739112890911
3 0.739085133385
4 0.739085133215
5 0.739085133215Hint: The number of correct digits roughly doubles every step: Newton's method converges quadratically near a simple root.
Show solution
import math
f = lambda x: math.cos(x) - x
df = lambda x: -math.sin(x) - 1
x = 1.0
for i in range(5):
if df(x) == 0:
print("f'(x) = 0, cannot take a Newton step")
break
x = x - f(x) / df(x)
print(i + 1, f"{x:.12f}")1 0.750363867840
2 0.739112890911
3 0.739085133385
4 0.739085133215
5 0.739085133215
Exercise 3: Simpson's rule for
has no elementary antiderivative; its exact value is . Complete Simpson's rule with : .
import math
def simpson(f, a, b, n):
h = (b - a) / n
total = f(a) + f(b)
# TODO: add 4*f(x_k) for odd k and 2*f(x_k) for even k, 0 < k < n
return total * h / 3
approx = simpson(lambda x: math.exp(-x * x), 0, 1, 10)
exact = math.sqrt(math.pi) / 2 * math.erf(1)
print(f"Simpson n=10: {approx:.10f}")
print(f"exact : {exact:.10f}")
print(f"error : {abs(approx - exact):.2e}")Simpson n=10: 0.0455959814
exact : 0.7468241328
error : 7.01e-01
Expected output when solved:
Simpson n=10: 0.7468249483
exact : 0.7468241328
error : 8.15e-07Hint: Simpson's error is , so even with the error should be below .
Show solution
import math
def simpson(f, a, b, n):
h = (b - a) / n
total = f(a) + f(b)
for k in range(1, n):
total += (4 if k % 2 else 2) * f(a + k * h)
return total * h / 3
approx = simpson(lambda x: math.exp(-x * x), 0, 1, 10)
exact = math.sqrt(math.pi) / 2 * math.erf(1)
print(f"Simpson n=10: {approx:.10f}")
print(f"exact : {exact:.10f}")
print(f"error : {abs(approx - exact):.2e}")Simpson n=10: 0.7468249483
exact : 0.7468241328
error : 8.15e-07
Exercise 4: A logistic population by Euler
A population follows with . Simulate it with Euler's method () up to and compare with the exact solution .
import math
r, K, P0, h, T = 0.5, 1000, 100, 0.1, 10
P = P0
for step in range(round(T / h)):
dP = 0.0 # TODO: the logistic rate r * P * (1 - P / K)
P += h * dP
exact = K / (1 + (K / P0 - 1) * math.exp(-r * T))
print(f"Euler P(10) = {P:.3f}")
print(f"exact P(10) = {exact:.3f}")Euler P(10) = 100.000
exact P(10) = 942.826
Expected output when solved:
Euler P(10) = 943.527
exact P(10) = 942.826Hint: Euler's method overshoots slightly during the fast-growth phase. Halving should roughly halve the error.
Show solution
import math
r, K, P0, h, T = 0.5, 1000, 100, 0.1, 10
P = P0
for step in range(round(T / h)):
dP = r * P * (1 - P / K)
P += h * dP
exact = K / (1 + (K / P0 - 1) * math.exp(-r * T))
print(f"Euler P(10) = {P:.3f}")
print(f"exact P(10) = {exact:.3f}")Euler P(10) = 943.527
exact P(10) = 942.826
Exercise 5: The area of a cardioid
Find the area enclosed by numerically with (midpoint sums, 1000 sectors) and compare with the exact .
import math
r = lambda th: 1 + math.cos(th)
n = 1000
dth = 2 * math.pi / n
area = 0.0
for k in range(n):
th = (k + 0.5) * dth
# TODO: add the area of the thin sector, (1/2) * r(th)^2 * dth
print(f"area ≈ {area:.6f} 3π/2 = {3 * math.pi / 2:.6f}")area ≈ 0.000000 3π/2 = 4.712389
Expected output when solved:
area ≈ 4.712389 3π/2 = 4.712389Hint: By hand: , and over a full turn the term integrates to 0 while integrates to .
Show solution
import math
r = lambda th: 1 + math.cos(th)
n = 1000
dth = 2 * math.pi / n
area = 0.0
for k in range(n):
th = (k + 0.5) * dth
area += 0.5 * r(th) ** 2 * dth
print(f"area ≈ {area:.6f} 3π/2 = {3 * math.pi / 2:.6f}")area ≈ 4.712389 3π/2 = 4.712389
. The midpoint sum of a smooth periodic function over a full period is extremely accurate, so all six decimals agree.
Exercise 6: How many terms for ?
For the series alternates with decreasing terms, so the error after stopping is less than the first omitted term. Add terms until the next term would be below , and report how many you used.
import math
x, tol = 0.5, 1e-6
terms, s = 0, 0.0
# TODO: repeat: add the next term (-1)**(k+1) * x**k / k (k = terms + 1),
# and stop once the following term x**(k+1) / (k+1) is below tol
print(f"terms used: {terms}")
print(f"sum = {s:.8f} ln 1.5 = {math.log(1.5):.8f} error = {abs(s - math.log(1.5)):.1e}")terms used: 0
sum = 0.00000000 ln 1.5 = 0.40546511 error = 4.1e-01
Expected output when solved:
terms used: 15
sum = 0.40546576 ln 1.5 = 0.40546511 error = 6.5e-07Hint: You need ; at it is .
Show solution
import math
x, tol = 0.5, 1e-6
terms, s = 0, 0.0
while True:
terms += 1
s += (-1) ** (terms + 1) * x ** terms / terms
if x ** (terms + 1) / (terms + 1) < tol:
break
print(f"terms used: {terms}")
print(f"sum = {s:.8f} ln 1.5 = {math.log(1.5):.8f} error = {abs(s - math.log(1.5)):.1e}")terms used: 15
sum = 0.40546576 ln 1.5 = 0.40546511 error = 6.5e-07
The actual error is below the bound , as the alternating series estimate promises.
Exercise 7: Curvature of a helix
For the helix compute at . The starter has , so it reports zero curvature, as for a straight line.
import numpy as np
t = 1.3
r1 = np.array([-2 * np.sin(t), 2 * np.cos(t), 1.0]) # r'(t)
r2 = np.array([0.0, 0.0, 0.0]) # TODO: r''(t)
kappa = np.linalg.norm(np.cross(r1, r2)) / np.linalg.norm(r1) ** 3
print(f"curvature at t = {t}: {kappa:.6f}")curvature at t = 1.3: 0.000000
Expected output when solved:
curvature at t = 1.3: 0.400000Hint: For the helix the curvature is constant, .
Show solution
import numpy as np
t = 1.3
r1 = np.array([-2 * np.sin(t), 2 * np.cos(t), 1.0]) # r'(t)
r2 = np.array([-2 * np.cos(t), -2 * np.sin(t), 0.0]) # r''(t)
kappa = np.linalg.norm(np.cross(r1, r2)) / np.linalg.norm(r1) ** 3
print(f"curvature at t = {t}: {kappa:.6f}")curvature at t = 1.3: 0.400000
and , so at every .
Exercise 8: The biggest box under a plane
A box has one corner at the origin and the opposite corner on the plane (). Maximise its volume with Lagrange multipliers: and , where .
import sympy as sp
x, y, z, lam = sp.symbols('x y z lam', positive=True)
V = x * y * z
g = x + 2*y + 3*z - 18
equations = [] # TODO: the three equations dV/dx = lam*dg/dx, ... and g = 0
sols = sp.solve(equations, [x, y, z, lam], dict=True) if equations else []
print("solutions:", sols)
for s in sols:
print("V =", V.subs(s))solutions: []
Expected output when solved:
solutions: [{lam: 6, x: 6, y: 3, z: 2}]
V = 36Hint: , , . Dividing pairs gives and : the three terms are equal.
Show solution
import sympy as sp
x, y, z, lam = sp.symbols('x y z lam', positive=True)
V = x * y * z
g = x + 2*y + 3*z - 18
equations = [sp.Eq(sp.diff(V, v), lam * sp.diff(g, v)) for v in (x, y, z)] + [sp.Eq(g, 0)]
sols = sp.solve(equations, [x, y, z, lam], dict=True) if equations else []
print("solutions:", sols)
for s in sols:
print("V =", V.subs(s))solutions: [{lam: 6, x: 6, y: 3, z: 2}]
V = 36
and give , , and .
Exercise 9: Two crossing cylinders
The solid inside both and has volume . Estimate it by Monte Carlo: sample points uniformly in the cube (volume 8) and multiply 8 by the fraction that lands inside.
import numpy as np
rng = np.random.default_rng(2024)
N = 400_000
x, y, z = rng.uniform(-1, 1, size=(3, N))
inside = np.zeros(N, dtype=bool) # TODO: x^2 + y^2 <= 1 and x^2 + z^2 <= 1
volume = 8 * inside.mean()
print(f"Monte Carlo volume ≈ {volume:.4f} exact 16/3 = {16 / 3:.4f}")Monte Carlo volume ≈ 0.0000 exact 16/3 = 5.3333
Expected output when solved:
Monte Carlo volume ≈ 5.3450 exact 16/3 = 5.3333Hint: By hand: the cross-section at a fixed is a square of side , so .
Show solution
import numpy as np
rng = np.random.default_rng(2024)
N = 400_000
x, y, z = rng.uniform(-1, 1, size=(3, N))
inside = (x**2 + y**2 <= 1) & (x**2 + z**2 <= 1)
volume = 8 * inside.mean()
print(f"Monte Carlo volume ≈ {volume:.4f} exact 16/3 = {16 / 3:.4f}")Monte Carlo volume ≈ 5.3450 exact 16/3 = 5.3333
The standard error of this estimate is with , so the difference of 0.012 you see is about two standard errors: normal for one run. More samples shrink it like .
Exercise 10: Work done by a gradient field
is the gradient of . Compute the work along the helix , , as a midpoint sum of , and compare with . The starter's is zero.
import numpy as np
F = lambda x, y, z: np.array([2 * x * y, x**2, np.cos(z)])
phi = lambda x, y, z: x**2 * y + np.sin(z)
n = 20_000
dt = 2 * np.pi / n
t = (np.arange(n) + 0.5) * dt
r = np.array([np.cos(t), np.sin(t), t / np.pi])
dr = np.zeros_like(r) # TODO: r'(t), one row per component
work = float(np.sum(F(*r) * dr) * dt)
print(f"line integral ≈ {work:.6f}")
print(f"phi(end) - phi(start) = {phi(1, 0, 2) - phi(1, 0, 0):.6f}")line integral ≈ 0.000000
phi(end) - phi(start) = 0.909297
Expected output when solved:
line integral ≈ 0.909297
phi(end) - phi(start) = 0.909297Hint: . The path starts at and ends at .
Show solution
import numpy as np
F = lambda x, y, z: np.array([2 * x * y, x**2, np.cos(z)])
phi = lambda x, y, z: x**2 * y + np.sin(z)
n = 20_000
dt = 2 * np.pi / n
t = (np.arange(n) + 0.5) * dt
r = np.array([np.cos(t), np.sin(t), t / np.pi])
dr = np.array([-np.sin(t), np.cos(t), np.full_like(t, 1 / np.pi)])
work = float(np.sum(F(*r) * dr) * dt)
print(f"line integral ≈ {work:.6f}")
print(f"phi(end) - phi(start) = {phi(1, 0, 2) - phi(1, 0, 0):.6f}")line integral ≈ 0.909297
phi(end) - phi(start) = 0.909297
Both give : the work of a gradient field depends only on the endpoints, so the whole helix contributes exactly what a straight segment would.
Test yourself
In Exercise 2 the Newton errors were about , , then . What property is this?
- Linear convergence
- Quadratic convergence
- Divergence
- Oscillation
Monte Carlo with samples estimated a volume with error about 0.006. How many samples are needed to reach about 0.0006?
Why is the work of along the helix equal to ?
- Because the helix is closed
- Because of the fundamental theorem for line integrals:
- Because is constant
- Because the curl of is non-zero