TExcelTAD
Home › Numerical Methods › Numerical Computing with Python

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.

python · try it yourself
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 x~\tilde{x} of xx:

absolute error=∣x~−x∣,relative error=∣x~−x∣∣x∣.\text{absolute error} = \lvert\tilde{x} - x\rvert, \qquad \text{relative error} = \frac{\lvert\tilde{x} - x\rvert}{\lvert x\rvert}.

The relative error tells you the number of correct significant digits: a relative error of 10−610^{-6} means about 6 correct digits. np.allclose(a, b, rtol, atol) checks ∣a−b∣≤atol+rtol ∣b∣\lvert a - b\rvert \le \text{atol} + \text{rtol}\,\lvert b\rvert, mixing both.

Convergence rates from data

Most methods have an error that behaves like E(h)≈ChpE(h) \approx Ch^p (step size hh) or E(n)≈Cn−pE(n) \approx Cn^{-p} (nn points). On a log-log plot this is a straight line with slope pp, and two measurements estimate pp:

p≈log⁡(E1/E2)log⁡(h1/h2).p \approx \frac{\log(E_1/E_2)}{\log(h_1/h_2)}.

Here is the trapezoid rule for ∫01ex dx\int_0^1 e^x\,dx, whose error should be O(h2)O(h^2) (Trapezoid and Simpson Rules):

python · try it yourself
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.

python · try it yourself
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 π\pi and you computed 3.14163.1416. What are the absolute and relative errors, and how many significant digits are correct?

Answer

About 7.3×10−67.3 \times 10^{-6} and 2.3×10−62.3 \times 10^{-6}; 5 to 6 digits.

Solution

∣3.1416−3.14159265…∣≈7.35×10−6\lvert 3.1416 - 3.14159265\ldots\rvert \approx 7.35 \times 10^{-6}, divided by π\pi gives 2.34×10−62.34 \times 10^{-6}.

Exercise 2: Estimate the order

A method gives errors 3.2×10−33.2 \times 10^{-3} at h=0.1h = 0.1 and 2.0×10−42.0 \times 10^{-4} at h=0.05h = 0.05. What is its order?

Answer

p=4p = 4.

Solution

log⁡(3.2×10−3/2.0×10−4)log⁡2=log⁡16log⁡2=4\frac{\log(3.2 \times 10^{-3} / 2.0 \times 10^{-4})}{\log 2} = \frac{\log 16}{\log 2} = 4.

Exercise 3: Midpoint rule order (code)

Measure the order of the midpoint rule h∑f(xi+h/2)h\sum f(x_{i} + h/2) for ∫01ex dx\int_0^1 e^x\,dx.

Answer

Order 2.

Solution
python · try it yourself
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 ChpCh^p, what does a log-log plot of error against hh show?

  1. A parabola
  2. A straight line with slope pp
  3. A horizontal line
  4. An exponential curve

A relative error of about 10−910^{-9} means roughly…

  1. 9 correct significant digits
  2. an error of 9
  3. 9 wrong digits
  4. nothing

Why should random test data come from np.random.default_rng(seed)?

  1. It is faster
  2. Results become reproducible, so outputs can be checked
  3. It gives better random numbers
  4. It is required by NumPy