Numerical Computing with Python
This course writes algorithms in NumPy and checks them against SciPy. A few habits make numerical experiments reliable and readable: vectorize instead of looping, time and count work honestly, measure errors on log scales, and estimate convergence rates from data. This lesson sets them up.
Vectorize the arithmetic
NumPy applies operations to whole arrays in compiled code. A loop that evaluates a function at a million points in pure Python is tens of times slower than the vectorized version.
import time
import numpy as np
x = np.linspace(0, 1, 200_000)
t0 = time.perf_counter()
y_loop = [np.sin(v) * np.exp(-v) for v in x]
t1 = time.perf_counter()
y_vec = np.sin(x) * np.exp(-x)
t2 = time.perf_counter()
print("same values:", np.allclose(y_loop, y_vec))
# Timings depend on the machine, so they are not printed here. Uncomment to see your speed-up:
# print(f"loop / vectorized time: {(t1 - t0) / (t2 - t1):.0f}x")same values: True
Timings vary between machines and runs, so the saved output shows only the check that both versions agree; uncomment the last line to see the speed-up on your device (typically tens of times). In the lessons we usually count operations instead of timing them.
Errors: absolute and relative
For an approximation of :
The relative error tells you the number of correct significant digits: a relative error of means about 6 correct digits. np.allclose(a, b, rtol, atol) checks , mixing both.
Convergence rates from data
Most methods have an error that behaves like (step size ) or ( points). On a log-log plot this is a straight line with slope , and two measurements estimate :
Here is the trapezoid rule for , whose error should be (Trapezoid and Simpson Rules):
import numpy as np
exact = np.e - 1
ns = np.array([10, 20, 40, 80, 160])
errs = []
for n in ns:
x = np.linspace(0, 1, n + 1)
errs.append(abs(np.trapezoid(np.exp(x), x) - exact))
errs = np.array(errs)
print("errors:", [f"{e:.2e}" for e in errs])
print("observed orders:", np.round(np.log(errs[:-1] / errs[1:]) / np.log(2), 3))
p = np.polyfit(np.log(1 / ns), np.log(errs), 1)[0]
print(f"least-squares slope on the log-log data: {p:.3f}")errors: ['1.43e-03', '3.58e-04', '8.95e-05', '2.24e-05', '5.59e-06']
observed orders: [2. 2. 2. 2.]
least-squares slope on the log-log data: 2.000
Plotting convergence
Error plots in this course use loglog (or semilogy when the error falls exponentially). A reference line with the expected slope makes the comparison visual.
import numpy as np
import matplotlib.pyplot as plt
h = np.logspace(-1, -4, 20)
err_fd = np.abs((np.sin(1 + h) - np.sin(1)) / h - np.cos(1))
err_cd = np.abs((np.sin(1 + h) - np.sin(1 - h)) / (2 * h) - np.cos(1))
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.loglog(h, err_fd, "o-", label="forward difference")
ax.loglog(h, err_cd, "s-", label="central difference")
ax.loglog(h, 0.5 * h, "k--", label="slope 1")
ax.loglog(h, 0.2 * h**2, "k:", label="slope 2")
ax.set_xlabel("h"); ax.set_ylabel("error"); ax.legend(fontsize=8)
print(f"h from 1e-1 to 1e-4: forward error falls {err_fd[0] / err_fd[-1]:.0f}x, central error falls {err_cd[0] / err_cd[-1]:.0f}x")h from 1e-1 to 1e-4: forward error falls 1021x, central error falls 999583x
Reproducibility
Random test data must come from a seeded generator, rng = np.random.default_rng(seed), so that every run (and the saved output) is identical. Avoid printing raw timings or memory addresses in examples.
In software
- NumPy delegates linear algebra to compiled BLAS and LAPACK libraries (OpenBLAS, MKL, Accelerate), written in C and Fortran and tuned for each CPU. The algorithms in this course are what those libraries implement.
- SciPy wraps decades-old, battle-tested Fortran codes: QUADPACK for integration, MINPACK for nonlinear equations, ODEPACK for stiff ODEs, ARPACK for sparse eigenvalues.
Exercises
Exercise 1: Relative error
The true value is and you computed . What are the absolute and relative errors, and how many significant digits are correct?
Answer
About and ; 5 to 6 digits.
Solution
, divided by gives .
Exercise 2: Estimate the order
A method gives errors at and at . What is its order?
Answer
.
Solution
.
Exercise 3: Midpoint rule order (code)
Measure the order of the midpoint rule for .
Answer
Order 2.
Solution
import numpy as np
exact = np.e - 1
errs = []
for n in (10, 20, 40, 80):
h = 1 / n
mid = np.arange(n) * h + h / 2
errs.append(abs(h * np.sum(np.exp(mid)) - exact))
print(np.round(np.log2(np.array(errs[:-1]) / np.array(errs[1:])), 3))[2. 2. 2.]
Test yourself
If the error behaves like , what does a log-log plot of error against show?
- A parabola
- A straight line with slope
- A horizontal line
- An exponential curve
A relative error of about means roughly…
- 9 correct significant digits
- an error of 9
- 9 wrong digits
- nothing
Why should random test data come from np.random.default_rng(seed)?
- It is faster
- Results become reproducible, so outputs can be checked
- It gives better random numbers
- It is required by NumPy