Calculus Exercises
Time to practise across the whole course: limits, derivatives, Newton's method, optimization, integrals, series, partial derivatives, double integrals and differential equations. 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: Work out the answer on paper first, even roughly, then let the code confirm it. If the code and your paper disagree, one of them has a bug, and finding out which is the real exercise.
| # | Exercise | Practises |
|---|---|---|
| 1 | Sneaking up on a limit | limits, numeric tables |
| 2 | Check a derivative | product rule, central differences |
| 3 | Cube root by Newton | Newton's method |
| 4 | The biggest box | optimization with SymPy |
| 5 | Simpson's rule | numerical integration |
| 6 | How many Taylor terms? | Taylor series, approximation error |
| 7 | Gradient and slope in a direction | gradient and directional derivative |
| 8 | A double integral on a grid | double integrals |
| 9 | When is the coffee drinkable? | separable equations, Euler's method |
Exercise 1: Sneaking up on a limit
Estimate by evaluating the expression for and . The starter prints 0 for each row.
import math
for h in [0.1, 0.01, 0.001, 0.0001]:
value = 0.0 # TODO: compute (e^h - 1) / h
print(f"h = {h:<7} value = {value:.6f}")h = 0.1 value = 0.000000
h = 0.01 value = 0.000000
h = 0.001 value = 0.000000
h = 0.0001 value = 0.000000
Expected output when solved:
h = 0.1 value = 1.051709
h = 0.01 value = 1.005017
h = 0.001 value = 1.000500
h = 0.0001 value = 1.000050Hint: The values approach the slope of at . The error is roughly .
Show solution
import math
for h in [0.1, 0.01, 0.001, 0.0001]:
value = (math.exp(h) - 1) / h
print(f"h = {h:<7} value = {value:.6f}")h = 0.1 value = 1.051709
h = 0.01 value = 1.005017
h = 0.001 value = 1.000500
h = 0.0001 value = 1.000050
The limit is 1, which is why : the slope of at 0 is exactly 1.
Exercise 2: Check a derivative
Differentiate by hand, then confirm your formula two ways at : with SymPy and with the central difference for .
import math
import sympy as sp
x = sp.symbols("x")
f = x**3 * sp.sin(x)
by_hand = 0 * x # TODO: your derivative of x^3 sin x
print("SymPy :", sp.diff(f, x))
print(f"by hand at 1: {float(by_hand.subs(x, 1)):.6f}")
fn = lambda t: t**3 * math.sin(t)
h = 1e-5
central = 0.0 # TODO: central difference at 1
print(f"central at 1: {central:.6f}")SymPy : x**3*cos(x) + 3*x**2*sin(x)
by hand at 1: 0.000000
central at 1: 0.000000
Expected output when solved: SymPy prints x**3*cos(x) + 3*x**2*sin(x), and both numbers are 3.064715.
Hint: Product rule: with and .
Show solution
import math
import sympy as sp
x = sp.symbols("x")
f = x**3 * sp.sin(x)
by_hand = 3 * x**2 * sp.sin(x) + x**3 * sp.cos(x)
print("SymPy :", sp.diff(f, x))
print(f"by hand at 1: {float(by_hand.subs(x, 1)):.6f}")
fn = lambda t: t**3 * math.sin(t)
h = 1e-5
central = (fn(1 + h) - fn(1 - h)) / (2 * h)
print(f"central at 1: {central:.6f}")SymPy : x**3*cos(x) + 3*x**2*sin(x)
by hand at 1: 3.064715
central at 1: 3.064715
Exercise 3: Cube root by Newton
Find as the root of with Newton's method , starting at . Print each of 5 iterations. The starter never moves.
x = 2.0
for i in range(1, 6):
# TODO: one Newton step for g(x) = x^3 - 10
print(f"iteration {i}: x = {x:.10f}")
print(f"check: x^3 = {x**3:.10f}")iteration 1: x = 2.0000000000
iteration 2: x = 2.0000000000
iteration 3: x = 2.0000000000
iteration 4: x = 2.0000000000
iteration 5: x = 2.0000000000
check: x^3 = 8.0000000000
Expected output when solved:
iteration 1: x = 2.1666666667
iteration 2: x = 2.1545036160
iteration 3: x = 2.1544346922
iteration 4: x = 2.1544346900
iteration 5: x = 2.1544346900
check: x^3 = 10.0000000000Hint: . The number of correct digits roughly doubles each iteration.
Show solution
x = 2.0
for i in range(1, 6):
x = x - (x**3 - 10) / (3 * x**2)
print(f"iteration {i}: x = {x:.10f}")
print(f"check: x^3 = {x**3:.10f}")iteration 1: x = 2.1666666667
iteration 2: x = 2.1545036160
iteration 3: x = 2.1544346922
iteration 4: x = 2.1544346900
iteration 5: x = 2.1544346900
check: x^3 = 10.0000000000
Exercise 4: The biggest box
From a sheet of card, cut a square of side from each corner and fold up the sides into an open box. Its volume is . Use SymPy to find the critical points, choose the one in , and print the maximum volume.
import sympy as sp
x = sp.symbols("x")
V = x * (30 - 2 * x)**2
critical = [] # TODO: solve V'(x) = 0
print("critical points:", critical)
best = 0 # TODO: the critical point inside (0, 15)
print("best cut:", best, "cm volume:", V.subs(x, best), "cm^3")critical points: []
best cut: 0 cm volume: 0 cm^3
Expected output when solved: critical points [5, 15], best cut 5 cm, volume 2000 .
Hint: gives a box with no bottom (). Check that to confirm a maximum.
Show solution
import sympy as sp
x = sp.symbols("x")
V = x * (30 - 2 * x)**2
critical = sp.solve(sp.diff(V, x), x)
print("critical points:", critical)
best = [c for c in critical if 0 < c < 15][0]
print("best cut:", best, "cm volume:", V.subs(x, best), "cm^3")
print("V''(5) =", sp.diff(V, x, 2).subs(x, best))critical points: [5, 15]
best cut: 5 cm volume: 2000 cm^3
V''(5) = -120
, so or , and confirms the maximum.
Exercise 5: Simpson's rule
Approximate (exactly 2) with Simpson's rule on subintervals: .
import math
def simpson(f, a, b, n):
h = (b - a) / n
total = f(a) + f(b)
# TODO: add 4*f for odd i and 2*f for even i, i = 1 .. n-1
return h / 3 * total
approx = simpson(math.sin, 0, math.pi, 10)
print(f"Simpson n=10: {approx:.8f} error {abs(approx - 2):.2e}")Simpson n=10: 0.00000000 error 2.00e+00
Expected output when solved:
Simpson n=10: 2.00010952 error 1.10e-04Hint:
total += (4 if i % 2 else 2) * f(a + i * h).
Show solution
import math
def simpson(f, a, b, n):
h = (b - a) / n
total = f(a) + f(b)
for i in range(1, n):
total += (4 if i % 2 else 2) * f(a + i * h)
return h / 3 * total
approx = simpson(math.sin, 0, math.pi, 10)
print(f"Simpson n=10: {approx:.8f} error {abs(approx - 2):.2e}")Simpson n=10: 2.00010952 error 1.10e-04
With only 11 function values the error is about ; doubling cuts it about 16 times (Simpson is fourth order).
Exercise 6: How many Taylor terms?
for Add terms until the partial sum is within of math.e, and print how many terms it took.
import math
total, k, term = 0.0, 0, 1.0
# TODO: loop while abs(total - math.e) >= 1e-6, adding term = 1/k! and increasing k
print(f"terms used: {k} sum = {total:.8f} error = {abs(total - math.e):.1e}")terms used: 0 sum = 0.00000000 error = 2.7e+00
Expected output when solved: terms used: 10, the sum 2.71828153, error about 3.0e-07.
Hint: Update the term with
term /= kafter increasing instead of callingmath.factorial.
Show solution
import math
total, k, term = 0.0, 0, 1.0
while abs(total - math.e) >= 1e-6:
total += term # adds 1/k!
k += 1
term /= k
print(f"terms used: {k} sum = {total:.8f} error = {abs(total - math.e):.1e}")terms used: 10 sum = 2.71828153 error = 3.0e-07
The terms leave out the tail , which is exactly the error printed.
Exercise 7: Gradient and slope in a direction
For , compute the gradient at with central differences, then the directional derivative in the direction of the vector .
f = lambda x, y: x**2 * y + y**3
h = 1e-6
fx = 0.0 # TODO: central difference in x at (1, 2)
fy = 0.0 # TODO: central difference in y at (1, 2)
print(f"gradient = ({fx:.4f}, {fy:.4f})")
u = (3, 4) # TODO: normalise u first
print(f"directional derivative = {fx * u[0] + fy * u[1]:.4f}")gradient = (0.0000, 0.0000)
directional derivative = 0.0000
Expected output when solved: gradient = (4.0000, 13.0000) and directional derivative = 12.8000.
Hint: . The unit vector is .
Show solution
f = lambda x, y: x**2 * y + y**3
h = 1e-6
fx = (f(1 + h, 2) - f(1 - h, 2)) / (2 * h)
fy = (f(1, 2 + h) - f(1, 2 - h)) / (2 * h)
print(f"gradient = ({fx:.4f}, {fy:.4f})")
u = (3 / 5, 4 / 5)
print(f"directional derivative = {fx * u[0] + fy * u[1]:.4f}")gradient = (4.0000, 13.0000)
directional derivative = 12.8000
Exactly: and .
Exercise 8: A double integral on a grid
Compute over the rectangle , with the midpoint rule on a grid using NumPy, and compare with the exact value.
import numpy as np
n = 100
dx, dy = 1 / n, 2 / n
xs = (np.arange(n) + 0.5) * dx # midpoints in x
ys = (np.arange(n) + 0.5) * dy # midpoints in y
X, Y = np.meshgrid(xs, ys)
approx = 0.0 # TODO: sum f at the midpoints times the cell area
print(f"midpoint: {approx:.6f}")
exact = 0.0 # TODO: work it out by hand (iterated integral)
print(f"exact: {exact:.6f}")midpoint: 0.000000
exact: 0.000000
Expected output when solved: midpoint 3.666600, exact 3.666667 ().
Hint: and .
Show solution
import numpy as np
n = 100
dx, dy = 1 / n, 2 / n
xs = (np.arange(n) + 0.5) * dx
ys = (np.arange(n) + 0.5) * dy
X, Y = np.meshgrid(xs, ys)
approx = np.sum(X + Y**2) * dx * dy
print(f"midpoint: {approx:.6f}")
exact = 1 + 8 / 3
print(f"exact: {exact:.6f}")midpoint: 3.666600
exact: 3.666667
The part is integrated exactly by the midpoint rule (it is linear); the small error comes only from .
Exercise 9: When is the coffee drinkable?
Coffee at 95 °C cools in a 20 °C room following ( in minutes). Step the equation with Euler's method () until drops below 60 °C, print the time, and compare with the exact time from the separable solution.
import math
T, t, h = 95.0, 0.0, 0.01
# TODO: while T >= 60, take an Euler step and advance t
print(f"Euler: below 60 °C at t = {t:.2f} min")
exact = 0.0 # TODO: solve 20 + 75 e^(-0.1 t) = 60 for t
print(f"exact: t = {exact:.2f} min")Euler: below 60 °C at t = 0.00 min
exact: t = 0.00 min
Expected output when solved: Euler t = 6.29 min, exact t = 6.29 min.
Hint: , so .
Show solution
import math
T, t, h = 95.0, 0.0, 0.01
while T >= 60:
T += h * (-0.1 * (T - 20))
t += h
print(f"Euler: below 60 °C at t = {t:.2f} min")
exact = 10 * math.log(75 / 40)
print(f"exact: t = {exact:.2f} min")Euler: below 60 °C at t = 6.29 min
exact: t = 6.29 min
Test yourself
In Exercise 3, why does Newton's method converge so quickly?
- Because is linear
- Near a simple root the error is roughly squared each step, so correct digits double
- Because it uses the second derivative
- It doesn't, it needs thousands of steps
In Exercise 4, why is rejected?
- It gives a negative volume
- It is a minimum: cutting 15 cm squares leaves no base,
- SymPy got it wrong
- It is not a critical point
In Exercise 8, which part of the integrand does the midpoint rule integrate exactly?
- Neither
- Both