Module 09
Numerical Methods and Scientific Computing
How do we turn theoretical mathematics into accurate, stable and efficient computer calculations?
- lessons
- 26
- duration
- 44 h 20 min
- concepts
- 157
- available in English
- 26 / 26
- completed by you
0 of 26
Where it fits
Prerequisites
Leads to
Overview
This module follows the whole path from representing numbers on a machine to GPU kernels: floating point and error analysis; direct and iterative numerical linear algebra; nonlinear equations, interpolation, approximation, quadrature and ODEs; forward and reverse automatic differentiation implemented from scratch; random numbers and Monte Carlo. The second half turns these algorithms into fast code using the memory hierarchy, vectorization, C++, CPU parallelism and programming the local RTX 4060, finishing at the frontier with randomized linear algebra and mixed precision.
Why it matters
Every loss that becomes NaN, incorrect gradient, irreproducible backtest and training run that will not fit in 8 GB is a problem from this module. The autograd engine built here is at the heart of GPT from scratch; integrators underpin simulated MuJoCo robots; Monte Carlo and solvers support quantitative work; and the performance model (roofline, memory and GPU) determines what can be trained on the local machine. For research, it helps distinguish model failure from numerical failure.
Lessons 26
- 01Machine numbers: IEEE 754 floating pointHow computers represent real numbers using a finite nonuniform set and what IEEE 754 guarantees for each operation, including binary64, binary32, binary16, bfloat16, FP8, ulps and special values.
- 02Rounding errors and numerically sound algorithmsApply the standard floating-point error model to cancellation, accurate summation and stable reformulations including logsumexp, softmax and online variance.
- 03Conditioning, stability and backward error analysisDistinguish intrinsically sensitive problems from unstable algorithms through condition numbers, forward and backward errors and linear-system diagnostics.
- 04Direct linear solvers: pivoted LU and CholeskyStudy finite-precision LU and Cholesky, Wilkinson's backward-error analysis and pivoting, operation counts, banded systems, factor reuse and iterative refinement.
- 05Orthogonalization and least squares: Householder, Givens and QROrthogonal transformations avoid amplifying errors. Study orthogonalization with Householder reflections and Givens rotations, losses of orthogonality in Gram–Schmidt, implicit Householder QR, updating factorizations with Givens, and rank-deficient least squares with pivoted QR and truncated SVD.
- 06Computing eigenvalues and the SVDCompute eigenvalues iteratively, from power iteration to the shifted QR algorithm used by LAPACK. Study SVD computation without forming AᵀA, eigenvalue sensitivity and the pseudospectra of nonnormal matrices.
- 07Sparse matrices and Krylov iterative methodsFor a matrix with millions of rows and mostly zero entries, use sparse representations and matrix–vector products in place of direct factorization. Study the limits of stationary methods, conjugate gradients and GMRES in Krylov spaces, and preconditioners that change practical convergence by orders of magnitude.
- 08Nonlinear equations: bisection, Newton and robust methodsSolve f(x) = 0 by bisection, fixed points, Newton and secant, measuring their convergence orders. Study how Brent combines robustness and speed, and use Newton and Broyden for systems. Build a robust solver to reuse with implicit methods and sampling.
- 09Interpolation: from Lagrange to splinesUse the barycentric formula for efficient, stable polynomial interpolation and Chebyshev nodes to avoid the Runge phenomenon. Build cubic splines and PCHIP for tasks such as yield curves, trajectories and tabulated data.
- 10Function approximation: Chebyshev, minimax and FourierFind compact function approximations using orthogonal polynomials, Chebyshev coefficient decay and minimax approximation, as used for functions such as exp and sin. Then study the discrete Fourier transform, the FFT, aliasing and fast convolution.
- 11Numerical integration: from Newton-Cotes to GaussReview classical quadrature and advance to Richardson extrapolation, Gaussian quadrature as an eigenvalue problem, adaptive integration and exponential trapezoid convergence for periodic functions, ending with the curse of dimensionality.
- 12Ordinary differential equations: simulating dynamical systemsHow y' = f(t, y) becomes a reliable simulation: Euler and Runge–Kutta methods, adaptive step control, absolute stability, stiffness and implicit methods, and symplectic integrators preserving energy over millions of steps. These underlie physical simulators such as MuJoCo, ODE-based diffusion samplers and Hamiltonian Monte Carlo.
- 13Numerical derivatives: finite differences, complex step and symbolic differentiationUnderstand the limits of alternatives to automatic differentiation: finite differences trade truncation against rounding, complex step avoids cancellation for analytic functions, and symbolic expressions can grow uncontrollably. Build a gradient checker for later AD engines.
- 14Automatic differentiation I: forward mode and dual numbersAutomatic differentiation applies the chain rule to a program's evaluation trace and computes derivatives to machine precision. Build forward mode with dual numbers, formalize Jacobian–vector products and use Jacobians for Newton and simulation sensitivities.
- 15Automatic differentiation II: reverse mode and general backpropagationReverse mode computes the full gradient of a scalar function at a cost comparable to evaluating it, making it possible to train models with billions of parameters or calibrate simulations with thousands. Build a tape-based reverse engine for arbitrary scientific programs, verify it with the dot-product test against forward mode, and apply it to a simulation gradient before comparing it with torch.autograd. The tensor engine for neural networks is built in m15.
- 16Automatic differentiation III: higher order, iterative solvers, adjoints and checkpointingCompose modes to obtain Hessian–vector products without forming the Hessian, choose a Jacobian strategy, write custom derivative rules, differentiate iterative solvers, decide between discrete and continuous adjoints, and control memory with binomial checkpointing. Turn the mathematical theory from m03 into algorithms with controlled cost and memory for second-order optimizers, Deep Equilibrium Models and Neural ODEs.
- 17Random numbers on a computer: generators and samplingMonte Carlo, weight initialization and dropout rely on a deterministic generator that imitates randomness. Study classical and modern generators (LCG, Mersenne Twister, PCG and Philox), uniform floats from bits, counter-based generators on GPUs, and algorithms transforming uniforms into distributions: numerical inversion, rejection, Ziggurat, alias and Gumbel-max. Practical seed and stream management for reproducibility is covered in m00.
- 18Monte Carlo: integration, error and stochastic simulationMonte Carlo turns integrals and expectations into sample averages, with error decreasing as N^(-1/2) regardless of dimension. Formalize the estimator, error and confidence intervals, see when it beats quadrature and when it fails with heavy tails or rare events, and build a discrete-event simulator. Variance reduction and quasi-Monte Carlo are covered in m29.
- 19Memory hierarchy, locality and the roofline modelOn modern hardware moving data costs far more than operating on it. Study the memory hierarchy, cache lines, array layout and tiling, and introduce the roofline model, which uses compute peak and bandwidth to determine whether a kernel is memory-bound or compute-bound. Measurements on the course's i9-14900HX use pointer-chasing latency and STREAM bandwidth microbenchmarks.
- 20Vectorization in depth: SIMD, memory traffic, recurrences and the BLAS stackExplore why vectorized code is fast and when it stops being so from the hardware perspective. Building on NumPy's memory model from m00, study SIMD instructions and barriers to their use, memory traffic from expression temporaries, vectorization of seemingly sequential recurrences, and the high-performance GEMM anatomy and BLAS and LAPACK stack beneath NumPy and SciPy.
- 21Modern C++ for scientific computingThe C++ essentials for reading and writing high-performance numerical code: the compilation model, memory and RAII, the templates behind Eigen, undefined behavior and the sanitizers that detect it, and what the compiler does (and undoes) with -O3, autovectorization and -ffast-math. Compare the same kernel in Python, NumPy and C++ on the local machine.
- 22Compiling the hot loop: Numba, pybind11 and fair comparisonsWhen NumPy is not enough, compile. Understand the interpreter's overhead, accelerate code with Numba, write C++ extensions with pybind11 or nanobind that receive arrays without copies and release the GIL, and compare the options rigorously on the same kernel to know what to choose and when it is not worthwhile.
- 23CPU parallelism: threads, processes and speedup lawsThe i9-14900HX has 24 heterogeneous cores and most Python code uses one. Study Amdahl's and Gustafson's laws, threads versus processes and the GIL (including free-threaded Python), OpenMP in C++, races and false sharing, and load balancing between P-cores and E-cores, measuring strong and weak scaling on real problems.
- 24GPU I: architecture and the CUDA programming modelA GPU is not a CPU with many cores: it is a throughput machine hiding latency with thousands of threads. Study SMs, warps and SIMT, CUDA's thread, block and grid hierarchy, the memory hierarchy, coalescing, occupancy, divergence, and CPU–GPU transfers, all measured on the local RTX 4060 Laptop (Ada Lovelace, compute capability 8.9, 8 GB).
- 25GPU II: efficient kernels, tiled matmul and PyTorch on the RTX 4060From a working kernel to a fast one. Build shared-memory tiled matrix multiplication toward cuBLAS performance; study GPU reductions and scans, Tensor Cores and precision, fused-kernel design behind FlashAttention and torch.compile, and kernel profiling with Nsight Compute. Finish with massive Monte Carlo on the local GPU.
- 26Frontier: randomized numerical linear algebra and mixed precisionStudy randomized sketches for least squares, kernel approximations and trace estimation, alongside mixed-precision iterative refinement and probabilistic numerics.
Module capstone
A differentiable, accelerated physical-system simulator
Build a simulator of a double pendulum with friction (or a planar two-link robotic arm) with both a symplectic and an adaptive integrator. Differentiate it end to end using the custom forward- and reverse-mode AD engine (verified with the dot-product test) and PyTorch, then calibrate its physical parameters (masses, lengths and friction) from noisy observed trajectories using gradients, Newton-CG with Hessian-vector products and, for long horizons, the discrete adjoint with binomial checkpointing. Quantify parameter uncertainty with Monte Carlo over observation noise and reproducible random streams. Then optimize performance: a NumPy version vectorized over trajectory batches, a Numba or C++ kernel with OpenMP, and a batched RTX 4060 version. Deliver a report analyzing float32 versus float64 error (energy drift), a roofline with measured kernels and a fair performance comparison of all versions following lesson 22.
Check what you already know
- Decode an IEEE 754 bit pattern and calculate the ulp and unit roundoff of float32, float16 and bfloat16.
- Rewrite expressions with cancellation or overflow stably (logsumexp, softmax, log1p and one-pass variance).
- Distinguish ill-conditioning from instability and estimate correct digits using κ and backward error.
- Solve systems using pivoted LU or Cholesky without inverting the matrix, and justify pivoting.
- Explain why normal equations square the condition number and implement Householder QR.
- Describe power iteration and shifted QR, and explain why SVD is not computed using AᵀA.
- Implement preconditioned conjugate gradient and explain convergence in terms of the spectrum.
- Implement Newton's method and a safeguarded method, and measure convergence order.
- Choose between Chebyshev interpolation, splines and PCHIP and explain Runge's phenomenon.
- Use FFT for convolution without circular-convolution or aliasing errors and reason about Chebyshev series.
- Choose and apply quadrature rules (Gaussian, adaptive and periodic trapezoidal) and estimate their error.
- Detect stiffness, choose an ODE integrator and explain the advantage of symplectic integrators.
- Choose the optimal finite-difference step and build a gradient checker.
- Implement forward-mode AD with dual numbers and compute JVPs.
- Implement a tape-based reverse-mode AD engine and verify adjoints with the dot-product test.
- Compute Hessian-vector products by composing modes and choose between unrolling, implicit differentiation and checkpointing.
- Implement rejection sampling, Ziggurat and alias sampling, and explain why GPUs use counter-based generators.
- Give a confidence interval for a Monte Carlo estimator and recognize when it is unreliable.
- Calculate a kernel's arithmetic intensity and place it on a roofline model.
- Predict memory traffic for an array expression, vectorize a linear recurrence and explain why only level-3 BLAS approaches peak performance.
- Compile a C++ project with CMake, avoid undefined behavior and check whether a loop was vectorized.
- Write a zero-copy pybind11 extension or Numba kernel and compare them fairly.
- Apply Amdahl's law and parallelize without race conditions or oversubscription.
- Explain coalescing, occupancy and divergence, and write a simple CUDA kernel.
- Optimize a tiled matmul and decide whether a GPU operation is memory-bound or compute-bound.
- Explain sketch-and-precondition, RPCholesky and mixed-precision iterative refinement.
References
- Accuracy and Stability of Numerical Algorithms (2.ª ed.)
- Numerical Linear Algebra
- Matrix Computations (4.ª ed.)
- Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation (2.ª ed.)
- Scientific Computing: An Introductory Survey (2.ª ed. revisada)
- An Introduction to Numerical Analysis
- Numerical Mathematics (2.ª ed.)
- Numerical Recipes: The Art of Scientific Computing (3.ª ed.)
- Programming Massively Parallel Processors: A Hands-on Approach (4.ª ed.)