Exercise: numerical differentiation
Goal
By the end of this exercise you should be able to:
- derive forward, backward, central and second-derivative stencils from Taylor series, with their leading error term,
- build the weights of any stencil (one-sided, five-point) by solving a small linear system,
- choose the best step for each stencil from the balance of truncation and rounding error,
- improve a central difference by Richardson extrapolation, and say what
numDeriv::graddoes, - estimate a growth rate from noisy OD data without amplifying the noise: wider stencils and local fits,
- compute and check a gradient of a log-likelihood by finite differences, and choose its step relative to each parameter.
The by-hand part needs pen, paper and a pocket calculator. The code part checks your hand answers and then works with a full plate-reader time course.
Background
The running example is the logistic OD curve from Convergence and cost, \(N(t) = K / (1 + (K/N_0 - 1)e^{-rt})\) with \(K = 1.2\), \(N_0 = 0.05\), \(r = 0.8\) per hour. Its derivatives at \(t = 3\) h:
| \(N\) | \(N'\) | \(N''\) | \(N'''\) | \(N''''\) |
|---|---|---|---|---|
| 0.388788 | 0.210260 | 0.059212 | \(-0.042270\) | \(-0.061704\) |
Facts used below:
Stencils (error = leading Taylor term left over):
formula estimate of error \(\dfrac{N(t+h) - N(t)}{h}\) (forward) \(N'\) \(\tfrac{h}{2}N''\) \(\dfrac{N(t) - N(t-h)}{h}\) (backward) \(N'\) \(-\tfrac{h}{2}N''\) \(\dfrac{N(t+h) - N(t-h)}{2h}\) (central) \(N'\) \(\tfrac{h^2}{6}N'''\) \(\dfrac{-3N(t) + 4N(t+h) - N(t+2h)}{2h}\) (one-sided) \(N'\) \(-\tfrac{h^2}{3}N'''\) \(\dfrac{N(t+h) - 2N(t) + N(t-h)}{h^2}\) (second difference) \(N''\) \(\tfrac{h^2}{12}N''''\) Weights of any stencil. For offsets \(s_0, \dots, s_{n-1}\) (in units of \(h\)) the weights \(w_j\) of the \(m\)-th derivative solve \(\sum_j w_j\, s_j^k / k! = [k = m]\) for \(k = 0, \dots, n-1\); then \(N^{(m)}(t) \approx \sum_j w_j N(t + s_j h) / h^m\).
Best step. Truncation \(\approx C h^p\), rounding \(\approx \varepsilon |N| / h^k\) for the \(k\)-th derivative. Balance: \(h^* \approx \varepsilon^{1/(p+k)}\), i.e. \(\varepsilon^{1/2} \approx 1.5\times10^{-8}\) (forward), \(\varepsilon^{1/3} \approx 6\times10^{-6}\) (central), \(\varepsilon^{1/4} \approx 1.2\times10^{-4}\) (second difference), times \(\max(|t|, 1)\).
Richardson. If \(D(h) = N' + c_2h^2 + c_4h^4 + \dots\) (central difference), then \(\dfrac{4D(h/2) - D(h)}{3} = N' + O(h^4)\). Repeating with \(16\), \(64\), … gives a table of ever higher order.
Noise. With independent measurement errors of sd \(\sigma\) at spacing \(\Delta t\), the central difference of neighbours has noise sd \(\sigma/(\sqrt2\,\Delta t)\), the forward difference \(\sqrt2\,\sigma/\Delta t\). A half-width \(h = k\Delta t\) divides the noise by \(k\) but adds truncation error \(\tfrac{h^2}{6}|N'''|\).
Gradients. \(\partial f / \partial \theta_j\) is an ordinary derivative in \(\theta_j\) with the other parameters fixed: one difference per parameter, with a step scaled to \(|\theta_j|\).
The basic tools in each language. R has numDeriv::grad (Richardson); Python has scipy.differentiate.derivative (adaptive, Richardson-like) and scipy.optimize.approx_fprime (forward difference); our Rust crate list has no differentiation crate, so the Rust version is hand-written.
K <- 1.2; N0 <- 0.05; r <- 0.8 # OD units, per hour
od <- function(t) K / (1 + (K / N0 - 1) * exp(-r * t))
gr <- function(t) r * od(t) * (1 - od(t) / K) # exact N'(t)
h <- .Machine$double.eps^(1/3) # best step for central
cen <- (od(3 + h) - od(3 - h)) / (2 * h)
c(cen, cen - gr(3))
library(numDeriv)
grad(od, 3) - gr(3) # Richardson inside
# Output:
# [1] 2.102597e-01 1.179223e-11
# [1] 2.060019e-13import numpy as np
from scipy.differentiate import derivative
K, N0, r = 1.2, 0.05, 0.8
def od(t): return K / (1 + (K / N0 - 1) * np.exp(-r * t))
def gr(t): return r * od(t) * (1 - od(t) / K) # exact N'(t)
h = np.finfo(float).eps ** (1 / 3) # best step for central
cen = (od(3 + h) - od(3 - h)) / (2 * h)
print(cen, cen - gr(3))
print(derivative(od, 3.0).df - gr(3)) # Richardson-like, adaptive
# Output:
# 0.2102597348635064 1.17922338560561e-11
# 8.243405957841787e-15// rust/examples/finite_differences_background.rs — cargo run --example finite_differences_background
// Background: central difference at the best step, and a Richardson table.
// Rust has no numDeriv / scipy.differentiate in our crate list: both are hand-written.
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
fn gr(t: f64) -> f64 {
R * od(t) * (1.0 - od(t) / K) // exact N'(t)
}
fn main() {
let h = f64::EPSILON.powf(1.0 / 3.0); // best step for central
let cen = (od(3.0 + h) - od(3.0 - h)) / (2.0 * h);
println!("{} {:e}", cen, cen - gr(3.0));
// Richardson, 4 levels from h = 1e-4 * |x| (what numDeriv::grad does)
let mut d: Vec<f64> = (0..4)
.map(|i| { let h = 3e-4 / 2f64.powi(i); (od(3.0 + h) - od(3.0 - h)) / (2.0 * h) })
.collect();
for j in 1..4 {
let f = 4f64.powi(j as i32);
for i in (j..4).rev() { d[i] = (f * d[i] - d[i - 1]) / (f - 1.0); }
}
println!("{:e}", d[3] - gr(3.0));
}
// Output:
// 0.2102597348635064 1.17922338560561e-11
// 2.0602963779481342e-13All solutions below assume these definitions (K, N0, r, od, gr). Rust prints numbers in its own format (2.89e-3 rather than 2.89e-03); the values are the same unless the text says otherwise.
By hand
B1. Stencils from Taylor. (a) From the Taylor series of \(N(t-h)\), derive the backward difference and its leading error term. (b) Show that the average of the forward and the backward difference is the central difference. What happens to their \(\pm\tfrac{h}{2}N''\) error terms? (c) Using the derivative table above, predict the errors of the forward, central and second difference at \(t = 3\) with \(h = 0.2\).
B2. Weights by matching Taylor terms. (a) Find \(w_{-1}, w_0, w_1\) such that \(w_{-1}N(t-h) + w_0 N(t) + w_1 N(t+h) = h^2 N''(t) + O(h^4)\). Write down the three equations (for the \(N\), \(hN'\) and \(h^2N''\) terms) and solve them. (b) Without new algebra: what is the one-sided second-order formula at the last time point, using \(N(t)\), \(N(t-h)\), \(N(t-2h)\)? (Hint: replace \(h\) by \(-h\) in the formula at the first point.) (c) Why must the weights of every first- or second-derivative stencil add up to zero?
B3. A plate reader, by hand. The OD at \(t = 2.9\), \(3.0\), \(3.1\) h is \(0.368065\), \(0.388788\), \(0.410103\). (a) Compute the forward, backward and central estimates of \(N'(3)\) with \(h = 0.1\), and the second difference. Compare with the table. (b) The plate reader exports 3 decimals: \(0.368\), \(0.389\), \(0.410\). Recompute the central difference and the second difference. What happened to the second derivative? (c) How large can the rounding error of the second difference be, if each value is off by up to \(0.0005\)?
B4. The best step. (a) Central difference: minimise \(E(h) = a h^2 + b/h\) with \(a = |N'''|/6 = 0.00705\) and \(b = \varepsilon|N| = 8.6\times10^{-17}\). Give \(h^*\) and \(E(h^*)\). (b) Second difference: minimise \(E(h) = c h^2 + 4b/h^2\) with \(c = |N''''|/12 = 0.00514\). Give \(h^*\) and \(E(h^*)\). (c) Noisy data: replace \(b\) in (a) by the noise \(\sigma/\sqrt2\) with \(\sigma = 0.005\), and \(|N'''|\) by its maximum \(r^3K/8 = 0.0768\). What half-width \(h^*\) (in hours and in 10-minute steps) minimises the error?
B5. Richardson by hand. The central differences at \(t = 3\) are \(D(0.2) = 0.2099781463\) and \(D(0.1) = 0.2101892975\). (a) Compute \(R = \tfrac{4D(0.1) - D(0.2)}{3}\) and compare all three with \(N'(3) = 0.2102597349\). (b) The forward difference has error \(c_1h + c_2h^2 + \dots\). Find the combination of \(F(h)\) and \(F(h/2)\) that removes the \(c_1h\) term. Apply it to \(F(0.2) = 0.2158788766\) and \(F(0.1) = 0.2131473499\). (c) Your colleague applies Richardson to central differences of measured OD values. Why is that a bad idea?
B6. Noise in a derivative. A plate reader measures OD every 10 minutes with noise sd \(\sigma = 0.005\). (a) What is the noise sd of the forward difference of neighbours, and of the central difference of neighbours, in OD/h? (b) The same for measurements every 2 minutes. Compare with the peak growth rate \(rK/4 = 0.24\) OD/h. (c) The plate reader rounds to 3 decimals. Rounding errors are uniform on \([-0.0005, 0.0005]\), sd \(0.0005/\sqrt3\). Does the rounding matter next to \(\sigma\)? (d) What is the noise sd of the central difference with half-width \(h = 40\) min?
B7. Automatic differentiation by hand (forward mode). Evaluate \(N(3)\) as a chain of steps and carry the derivative with respect to \(t\) alongside (use \(r = 0.8\), \(K/N_0 - 1 = 23\), \(e^{-2.4} = 0.0907180\)):
| step | value | derivative (w.r.t. \(t\)) |
|---|---|---|
| \(v_1 = -r t\) | \(v_1' = -r\) | |
| \(v_2 = e^{v_1}\) | \(v_2' = v_2\,v_1'\) | |
| \(v_3 = 1 + 23\,v_2\) | \(v_3' = 23\,v_2'\) | |
| \(v_4 = K / v_3\) | \(v_4' = -K\,v_3' / v_3^2\) |
Fill in the table. Is \(v_4'\) an approximation? Which step size did you use?
B8. The cost of a gradient. One evaluation of a log-likelihood needs an ODE solve that takes 0.2 s. (a) How long does one gradient take for \(p = 3\) parameters with forward differences, central differences, and numDeriv::grad (8 evaluations per parameter)? And for \(p = 40\)? (b) A BFGS fit takes 100 iterations, each needing one gradient. How long does the \(p = 40\) fit take with central differences? With reverse-mode AD at about 3 evaluations per gradient?
In code
C1. Four stencils and their V. At \(t = 3\), compute the absolute errors of the forward, central, one-sided (fact 1) and second-difference formulas for \(h = 10^{-1}, 10^{-2}, \dots, 10^{-12}\). Print the table. Which \(h\) is best for each formula? Compare with B4 and fact 3. Fit the slope of \(\log_{10}\) error against \(\log_{10} h\) for \(h \ge 10^{-3}\).
C2. Weights by solving a linear system. Write fd_weights(s, m) that returns the weights of the \(m\)-th derivative for offsets s (fact 2). Check it against B2(a), the central difference and the one-sided formula. Then find the five-point weights for \(N'\) with offsets \(-2, \dots, 2\), use them on the OD curve at \(t = 3\) with \(h = 0.1\) and \(h = 0.05\), and read off the order from the error ratio.
C3. A Richardson table. Write richardson(f, x, h0, levels) that fills a lower-triangular table: column 1 holds central differences at \(h_0, h_0/2, h_0/4, \dots\); column \(j+1\) combines neighbours in column \(j\) with weights \(\tfrac{4^j}{4^j - 1}\) and \(-\tfrac{1}{4^j - 1}\). Print the errors of the table for \(h_0 = 0.4\) and for \(h_0 = 10^{-4}\), four levels each. Which is better, and why? Compare with the library derivative from the Background.
C4. Growth rate from plate-reader data. These are the plate-reader values from the lecture (61 time points, every 10 min, 3 decimals):
t <- seq(0, 10, by = 1/6) # hours, every 10 min
y <- c(0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203)t = np.arange(61) / 6 # hours, every 10 min
y = np.array([0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203])// rust/examples/finite_differences_c4.rs — the data as a constant (also in _c5, _c6)
const Y: [f64; 61] = [
0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203];
// time of point i: i as f64 / 6.0 hours- Compute the central differences of neighbours and their rms error against the true growth rate
gr(t). What are the smallest and largest values? Compare with B6(a). - Repeat with half-width \(k = 1, \dots, 8\) steps, \((y_{i+k} - y_{i-k})/(2k\Delta t)\). Which \(k\) gives the smallest rms error? Compare with B4(c).
- With the best \(k\), what is the maximum growth rate and when does it occur? (True: 0.240 OD/h at 3.92 h.)
C5. Smooth first: a local straight-line fit. Fit a least-squares line to the \(2m+1\) points around each \(t_i\) and take its slope: \[\widehat{N'}(t_i) = \frac{\sum_{j=-m}^{m} j\,y_{i+j}}{\Delta t \sum_{j=-m}^{m} j^2}.\] Compute it for \(m = 1, \dots, 8\) with its rms error. Which \(m\) is best, and how does it compare with C4(b) at the same width? What is the maximum growth rate now?
C6. Gradient of a log-likelihood. Fit \(\theta = (r, K, N_0)\) to the data of C4 with \(\ell(\theta) = -\sum_i (y_i - N(t_i;\theta))^2/(2\sigma^2)\), \(\sigma = 0.005\). The exact gradient is \(\partial\ell/\partial\theta_j = \sum_i \frac{y_i - N_i}{\sigma^2}\,\frac{\partial N_i}{\partial\theta_j}\) with, writing \(E = e^{-rt}\) and \(D = 1 + (K/N_0 - 1)E\), \[\frac{\partial N}{\partial r} = t\,N\Big(1 - \frac{N}{K}\Big),\qquad \frac{\partial N}{\partial K} = \frac1D - \frac{KE}{N_0D^2},\qquad \frac{\partial N}{\partial N_0} = \frac{K^2E}{N_0^2D^2}.\] (a) At \(\theta = (0.75, 1.15, 0.06)\), compute the relative error of the forward (\(h_j = 10^{-8}\max(|\theta_j|,1)\)) and central (\(h_j = 6\times10^{-6}\max(|\theta_j|,1)\)) gradients, and of the library gradient (R: numDeriv::grad; Python: approx_fprime). (b) At the maximum \(\hat\theta = (0.79542677, 1.20245707, 0.050760766)\), the exact gradient is almost zero. Compute the central-difference gradient with a fixed absolute step \(10^{-3}\) (what optim uses by default), with a relative step \(10^{-3}|\theta_j|\) and with \(6\times10^{-6}|\theta_j|\). Which components are wrong, and why? (c) Gradient check. Introduce a bug in the exact gradient: drop the factor \(t\) in \(\partial N/\partial r\). Compare with the central-difference gradient. How would you spot the bug if you did not know where it was?
Explore
The demo below differentiates the plate-reader data of C4 (the same 61 values) in your browser, with one of three estimators of half-width \(k\) samples (\(h = k \cdot 10\) min): the central difference \((y_{i+k} - y_{i-k})/(2k\,\Delta t)\) (\(k = 1\) is the difference of neighbours), the local line of C5 (least-squares slope over the \(2k+1\) points) and Richardson \(\tfrac{4D(h) - D(2h)}{3}\) of two central differences. Panel (a) shows the data, the points the estimator uses at the selected time and the slope it finds; click or drag in (a) or (b) to move the selected time. Panel (b) compares the estimated growth rate with the true \(N'(t) = rN(1 - N/K)\), with the neighbour differences in grey. Panel (c) shows the rms error against \(h\) for every \(k\) from 1 to 12: the measured error (strong; the other two estimators faint), the noise model \(\sigma\sqrt{\sum_j w_j^2}\) for the estimator’s weights \(w_j\) (dashed) and the truncation error, the same estimator applied to the exact OD values (dotted). The switch exact OD replaces the data by the noise-free curve. As in C4, the rms error is taken over the time points where the stencil fits, and the readout says how many are lost at each end.
E1. (neighbours: noise wins) Click neighbours. Read the rms error, the predicted noise sd and the truncation rms, and the maximum growth rate. Then switch to exact OD. How much of the error of the neighbour differences is truncation? Where in panel (b) are the estimates least useful, relative to the growth rate itself?
rms error \(0.0203\) OD/h, noise sd \(0.021\) (B6(a)), truncation rms \(1.5\times10^{-4}\): the noise is more than 100 times the truncation error, so with exact OD values the same formula is almost perfect (rms \(1.5\times10^{-4}\), the curve in (b) lies on the truth). With the measurements the maximum is \(0.270\) at \(4.00\) h, 13 % above the true \(0.240\): the maximum of noisy estimates is biased upwards, because it picks the largest noise. The noise sd is the same everywhere, but in the first half hour the true rate is only \(0.04\)–\(0.05\) OD/h and after 8 h below \(0.035\) OD/h, so there the noise (\(0.021\)) is half the signal or more, and some estimates are even negative (\(-0.033\) in the stationary phase).
E2. (the V with noise) Stay with central on the plate-reader data and drag \(k\) from 1 to 12. Follow the marker in panel (c), and the dashed and dotted lines. At which \(k\) is the rms error smallest, and where do the noise model and the truncation cross? What happens to the peak in panel (b), and to the ends, at \(k = 12\)?
The error falls from \(0.0203\) (\(k = 1\)) to \(0.0092\), \(0.0065\) and a minimum of \(0.0053\) at \(k = 4\) (40 min), then rises again: \(0.0058\), \(0.0069\), …, \(0.023\) at \(k = 12\). The noise model falls like \(1/h\) (\(0.0053\) at \(k = 4\), \(0.0042\) at \(k = 5\)), the truncation rises like \(h^2\) (\(0.0025\) at \(k = 4\), \(0.0040\) at \(k = 5\)); they cross near \(k = 5\), and the measured minimum sits just before the crossing, as in B4(c). At \(k = 12\) the curve in (b) is smooth but too flat: the maximum is \(0.201\) OD/h instead of \(0.240\), and 12 points (2 h) are lost at each end, so the whole lag phase has no estimate. This is the V of Convergence and cost with the noise \(\sigma\) in the place of \(\varepsilon|N|\), and the best step is 40 minutes instead of \(10^{-8}\).
E3. (use all the points) Click local line k = 4 and compare its rms error, noise sd and truncation rms with those of central k = 4 (shown in the readout). Then vary \(k\): which \(k\) is best for the local line? Why does it have less noise at the same half-width?
Local line, \(k = 4\): rms \(0.00405\), noise sd \(0.0039\), truncation \(0.0019\); central, \(k = 4\): \(0.00528\), \(0.0053\), \(0.0025\). The local line is better on both counts. \(k = 4\) and \(k = 5\) tie at \(0.00405\) (\(k = 6\): \(0.0047\)). The central difference uses only the two outermost of the 9 points in the window; the least-squares slope uses all of them (panel (a) highlights 8 points with non-zero weight), so it averages more noise: its noise sd is \(\sigma / (\Delta t \sqrt{\sum j^2}) = 0.005 \cdot 6/\sqrt{60} = 0.0039\) instead of \(\sigma/(\sqrt2\, h) = 0.0053\). Maximum \(0.234\) at \(4.33\) h, as in C5.
E4. (Richardson and noise) Click Richardson and exact OD with \(k = 1\). Compare its rms error with the central difference at the same \(k\) (readout). How many digits does the extrapolation gain? Now switch back to the plate-reader data (or click Richardson k = 1). What happens, and why? Finally, find the \(k\) at which Richardson does best on the measured data, and read off which time span it covers.
Exact OD: \(1.0\times10^{-6}\) against \(1.54\times10^{-4}\) for the central difference, a factor 150, about two digits gained; the dotted line in (c) is much steeper (slope 4 instead of 2). On the measured data the rms error rises to \(0.0269\) (central: \(0.0203\)), and the maximum is \(0.281\): the noise sd grows from \(0.021\) to \(0.029\), since the weights \(\tfrac43\) and \(-\tfrac13\) amplify the noise of both differences (B5(c)), and the truncation it removes was negligible anyway. Richardson is best at \(k = 5\)–\(7\) (rms \(0.0044\), \(0.0043\), \(0.0042\)), no better than the local line at \(k = 4\), and at \(k = 7\) it needs 14 points on each side: estimates only from 2.33 h to 7.67 h. With noisy data, extrapolation spends its effort on the wrong error.
Hints
Write \(N(t \pm h) = N \pm hN' + \tfrac{h^2}{2}N'' \pm \tfrac{h^3}{6}N''' + \tfrac{h^4}{24}N'''' \pm \dots\). For a stencil, add \(w_j\) times the row for each point and collect the coefficient of each derivative. For B2(a) the equations are \(w_{-1} + w_0 + w_1 = 0\), \(-w_{-1} + w_1 = 0\), \(\tfrac12 w_{-1} + \tfrac12 w_1 = 1\).
Differentiate \(E(h)\) and set it to zero: for \(ah^2 + b/h\), \(2ah = b/h^2\), so \(h^3 = b/(2a)\). For \(ch^2 + 4b/h^2\), \(2ch = 8b/h^3\), so \(h^4 = 4b/c\).
If \(e_1\) and \(e_2\) are independent with sd \(\sigma\), then \(e_2 - e_1\) has sd \(\sqrt2\,\sigma\). Dividing by a constant \(c\) divides the sd by \(c\). In R, y[i + k] - y[i - k] with i <- (k + 1):(n - k) takes all differences at once; in Python, y[2*k:] - y[:-2*k].
Build the matrix with outer (R) or a nested list comprehension (Python), row \(k\) = \(s_j^k/k!\), and solve with solve (R) or np.linalg.solve (Python); in Rust, nalgebra’s DMatrix::lu().solve. For a five-point stencil the error is \(O(h^4)\), so halving \(h\) should divide it by 16.
Fill column 1 in a loop over \(i\); then for each column \(j \ge 2\), loop over the rows \(i \ge j\) and combine A[i, j-1] (the smaller step) with A[i-1, j-1]. Library equivalents: numDeriv::grad (R), scipy.differentiate.derivative (Python).
The formula is the slope of lm(y ~ t) on the window, with the window centred so that \(\sum j = 0\). The library route, covered in Splines: smooth.spline followed by predict(fit, t, deriv = 1) in R, scipy.interpolate.make_smoothing_spline followed by .derivative() in Python. np.gradient is the central difference of neighbours: it does not smooth.
Loop over the parameters; build a vector e of zeros with h[j] in position j, and difference f(x + e) and f(x - e). Compare with the exact gradient through the relative error \(|g_\text{fd} - g|/|g|\). R’s optim documents ndeps and parscale under Details; Python’s scipy.optimize.minimize takes jac= for an exact gradient.
Solutions
B1. (a) \(N(t-h) = N - hN' + \tfrac{h^2}{2}N'' - \dots\), so \(N(t) - N(t-h) = hN' - \tfrac{h^2}{2}N'' + \dots\) and \(\dfrac{N(t) - N(t-h)}{h} = N' - \tfrac{h}{2}N'' + O(h^2)\). (b) \(\tfrac12\Big(\tfrac{N(t+h) - N(t)}{h} + \tfrac{N(t) - N(t-h)}{h}\Big) = \tfrac{N(t+h) - N(t-h)}{2h}\). The errors \(+\tfrac{h}{2}N''\) and \(-\tfrac{h}{2}N''\) cancel; the next terms, \(\pm\tfrac{h^2}{6}N'''\), have the same sign in both and survive: \(\tfrac{h^2}{6}N'''\). (c) Forward: \(\tfrac{0.2}{2}\cdot 0.059212 = 0.0059\) (actual \(0.0056\); the \(h^2\) term \(-0.00028\) is not negligible at \(h = 0.2\)). Central: \(\tfrac{0.04}{6}\cdot(-0.042270) = -2.82\times10^{-4}\) (actual \(-2.82\times10^{-4}\)). Second difference: \(\tfrac{0.04}{12}\cdot(-0.061704) = -2.06\times10^{-4}\).
B2. (a) \(N\) terms: \(w_{-1} + w_0 + w_1 = 0\). \(hN'\) terms: \(-w_{-1} + w_1 = 0\). \(h^2N''\) terms: \(\tfrac12 w_{-1} + \tfrac12 w_1 = 1\). So \(w_{-1} = w_1 = 1\), \(w_0 = -2\): the \((1, -2, 1)\) stencil. (b) \(N'(t) \approx \dfrac{3N(t) - 4N(t-h) + N(t-2h)}{2h}\) (replace \(h\) by \(-h\) in \(\tfrac{-3N(t) + 4N(t+h) - N(t+2h)}{2h}\); the signs flip because the denominator \(2h\) flips). (c) Apply the stencil to a constant function \(N \equiv 1\): every derivative is 0, so \(\sum_j w_j \cdot 1\) must be 0. It is the first of the Taylor equations.
B3. (a) Forward \((0.410103 - 0.388788)/0.1 = 0.21315\) (error \(+0.0029\)). Backward \((0.388788 - 0.368065)/0.1 = 0.20723\) (error \(-0.0030\)). Central \((0.410103 - 0.368065)/0.2 = 0.21019\) (error \(-0.00007\)). Second difference \((0.410103 - 0.777576 + 0.368065)/0.01 = 0.000592/0.01 = 0.0592\) (true \(0.059212\)). (b) Central: \((0.410 - 0.368)/0.2 = 0.210\), still fine. Second difference: \((0.410 - 0.778 + 0.368)/0.01 = 0\). The curvature has vanished: the numerator \(0.000592\) is smaller than the rounding of the data. (c) With weights \(1, -2, 1\) the numerator can be off by \((1 + 2 + 1)\cdot 0.0005 = 0.002\), divided by \(h^2 = 0.01\): up to \(0.2\), three times the true \(N''\). Second derivatives of measured data need much wider stencils or a fitted model.
B4. (a) \(h^* = (b/2a)^{1/3} = (8.6\times10^{-17}/0.0141)^{1/3} = 1.8\times10^{-5}\); \(E(h^*) = 0.00705\cdot 3.3\times10^{-10} + 8.6\times10^{-17}/1.8\times10^{-5} = 2.4\times10^{-12} + 4.7\times10^{-12} \approx 7\times10^{-12}\). Close to \(\varepsilon^{1/3} = 6\times10^{-6}\); C1 finds the best \(h\) at \(10^{-5}\) with error \(9\times10^{-13}\) (rounding errors partly cancel there by luck). (b) \(h^* = (4b/c)^{1/4} = (6.7\times10^{-14})^{1/4} = 5.1\times10^{-4}\); \(E(h^*) = 1.3\times10^{-9} + 1.3\times10^{-9} \approx 2.7\times10^{-9}\). The second derivative keeps only about 8–9 digits. (c) \(a = 0.0768/6 = 0.0128\), \(b = 0.005/\sqrt2 = 0.00354\): \(h^* = (0.00354/0.0256)^{1/3} = 0.52\) h, about 3 steps of 10 min (30 min); \(E \approx 0.010\) OD/h at the inflection point, where \(|N'''|\) is largest. C4 finds \(k = 4\) best on average over the whole curve, since \(|N'''|\) is smaller elsewhere.
B5. (a) \(R = (4\cdot0.2101892975 - 0.2099781463)/3 = 0.2102596812\). Errors: \(D(0.2)\): \(-2.8\times10^{-4}\); \(D(0.1)\): \(-7.0\times10^{-5}\); \(R\): \(-5.4\times10^{-8}\), a thousand times smaller. (b) \(F(h) = N' + c_1h + \dots\), \(F(h/2) = N' + c_1h/2 + \dots\), so \(2F(h/2) - F(h) = N' + O(h^2)\). Here \(2\cdot0.2131473499 - 0.2158788766 = 0.2104158232\), error \(1.6\times10^{-4}\) instead of \(2.9\times10^{-3}\). (c) Richardson assumes the error is \(c_2h^2 + c_4h^4 + \dots\). Measurement noise is not; the weights \(\tfrac43\) and \(-\tfrac13\) add the noise of both estimates (sd grows by a factor \(\sqrt{(4/3)^2 + (1/3)^2} \approx 1.37\) for independent estimates), and every further level amplifies it again. With noisy data, use a wider stencil or smoothing.
B6. (a) Forward: \(\sqrt2\cdot0.005/(1/6) = 0.042\) OD/h. Central: \(0.005/(\sqrt2/6) = 0.021\) OD/h. (b) Every 2 min (\(\Delta t = 1/30\) h): forward \(0.21\), central \(0.11\) OD/h, about half of the peak growth rate 0.24. More frequent measurements make the derivative of neighbours worse. (c) \(0.0005/\sqrt3 = 0.00029\), about 17 times smaller than \(\sigma\) (and variances add: \(\sqrt{0.005^2 + 0.00029^2} = 0.00501\)). Not here; it would matter for a very precise instrument or a second derivative (B3). (d) \(0.005/(\sqrt2\cdot 4/6) = 0.0053\) OD/h.
B7.
| step | value | derivative |
|---|---|---|
| \(v_1 = -0.8\cdot3\) | \(-2.4\) | \(-0.8\) |
| \(v_2 = e^{v_1}\) | \(0.0907180\) | \(0.0907180\cdot(-0.8) = -0.0725744\) |
| \(v_3 = 1 + 23\,v_2\) | \(3.086513\) | \(23\cdot(-0.0725744) = -1.669211\) |
| \(v_4 = 1.2/v_3\) | \(0.388788\) | \(-1.2\cdot(-1.669211)/3.086513^2 = 0.210260\) |
\(v_4' = 0.210260 = N'(3)\), exact up to the rounding of the hand calculation. No step size at all: each line applies an exact derivative rule (the chain rule) to numbers. This is forward-mode AD; a library does the same for every operation in a program.
B8. (a) \(p = 3\): forward \(4\times0.2 = 0.8\) s, central \(6\times0.2 = 1.2\) s, numDeriv \(24\times0.2 = 4.8\) s. \(p = 40\): forward \(8.2\) s, central \(16\) s, numDeriv \(64\) s. (b) Central: \(100\times16\) s \(\approx 27\) min. Reverse-mode AD: \(100\times3\times0.2 = 60\) s, independent of \(p\). For large models, the gradient is the cost of fitting.
C1.
t0 <- 3; d1 <- gr(t0); d2 <- r * d1 * (1 - 2 * od(t0) / K)
h <- 10^-(1:12)
err <- data.frame(
h,
fwd = abs((od(t0 + h) - od(t0)) / h - d1),
cen = abs((od(t0 + h) - od(t0 - h)) / (2 * h) - d1),
one = abs((-3 * od(t0) + 4 * od(t0 + h) - od(t0 + 2 * h)) / (2 * h) - d1),
sec = abs((od(t0 + h) - 2 * od(t0) + od(t0 - h)) / h^2 - d2))
print(signif(err, 3))
sapply(err[-1], function(e) h[which.min(e)]) # best h per formula
ok <- h >= 1e-3 # truncation regime only
sapply(err[-1], function(e) unname(coef(lm(log10(e[ok]) ~ log10(h[ok])))[2]))
# Output:
# h fwd cen one sec
# 1 1e-01 2.89e-03 7.04e-05 1.56e-04 5.14e-05
# 2 1e-02 2.95e-04 7.05e-07 1.42e-06 5.14e-07
# 3 1e-03 2.96e-05 7.05e-09 1.41e-08 5.21e-09
# 4 1e-04 2.96e-06 6.98e-11 1.41e-10 7.82e-09
# 5 1e-05 2.96e-07 9.32e-13 1.20e-11 9.07e-07
# 6 1e-06 2.96e-08 4.90e-11 3.42e-11 1.49e-04
# 7 1e-07 1.99e-09 5.06e-10 2.17e-09 9.25e-03
# 8 1e-08 3.00e-09 2.29e-10 3.00e-09 6.14e-01
# 9 1e-09 1.92e-08 7.47e-08 8.56e-09 1.11e+02
# 10 1e-10 1.47e-07 4.08e-07 7.02e-07 1.11e+04
# 11 1e-11 5.70e-06 1.47e-07 1.12e-05 1.11e+06
# 12 1e-12 3.90e-05 1.65e-05 9.45e-05 1.11e+08
# fwd cen one sec
# 1e-07 1e-05 1e-05 1e-03
# fwd cen one sec
# 0.9946299 1.9999594 2.0219907 1.9968123t0 = 3.0
d1 = gr(t0); d2 = r * d1 * (1 - 2 * od(t0) / K)
h = 10.0 ** -np.arange(1, 13)
err = {
"fwd": np.abs((od(t0 + h) - od(t0)) / h - d1),
"cen": np.abs((od(t0 + h) - od(t0 - h)) / (2 * h) - d1),
"one": np.abs((-3 * od(t0) + 4 * od(t0 + h) - od(t0 + 2 * h)) / (2 * h) - d1),
"sec": np.abs((od(t0 + h) - 2 * od(t0) + od(t0 - h)) / h**2 - d2)}
print(" h fwd cen one sec")
for i in range(len(h)):
print(f"{h[i]:.0e}", *(f"{err[k][i]:.2e}" for k in err))
print("best h:", *(f"{k} {h[np.argmin(e)]:.0e}" for k, e in err.items()))
ok = h >= 1e-3 # truncation regime
print("slope: ", *(f"{k} {np.polyfit(np.log10(h[ok]), np.log10(e[ok]), 1)[0]:.4f}"
for k, e in err.items()))
# Output:
# h fwd cen one sec
# 1e-01 2.89e-03 7.04e-05 1.56e-04 5.14e-05
# 1e-02 2.95e-04 7.05e-07 1.42e-06 5.14e-07
# 1e-03 2.96e-05 7.05e-09 1.41e-08 5.21e-09
# 1e-04 2.96e-06 6.98e-11 1.41e-10 7.82e-09
# 1e-05 2.96e-07 9.32e-13 1.20e-11 9.07e-07
# 1e-06 2.96e-08 4.90e-11 3.42e-11 1.49e-04
# 1e-07 1.99e-09 5.06e-10 2.17e-09 9.25e-03
# 1e-08 3.00e-09 2.29e-10 3.00e-09 6.14e-01
# 1e-09 1.92e-08 7.47e-08 8.56e-09 1.11e+02
# 1e-10 1.47e-07 4.08e-07 7.02e-07 1.11e+04
# 1e-11 5.70e-06 1.47e-07 1.12e-05 1.11e+06
# 1e-12 3.90e-05 1.65e-05 9.45e-05 1.11e+08
# best h: fwd 1e-07 cen 1e-05 one 1e-05 sec 1e-03
# slope: fwd 0.9946 cen 2.0000 one 2.0220 sec 1.9968// rust/examples/finite_differences_c1.rs — cargo run --example finite_differences_c1
// C1: four stencils, their errors, best step and order.
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
// slope of the least-squares line through (x, y)
fn slope(x: &[f64], y: &[f64]) -> f64 {
let n = x.len() as f64;
let (mx, my) = (x.iter().sum::<f64>() / n, y.iter().sum::<f64>() / n);
let sxy: f64 = x.iter().zip(y).map(|(a, b)| (a - mx) * (b - my)).sum();
let sxx: f64 = x.iter().map(|a| (a - mx).powi(2)).sum();
sxy / sxx
}
fn main() {
let t0 = 3.0;
let d1 = R * od(t0) * (1.0 - od(t0) / K);
let d2 = R * d1 * (1.0 - 2.0 * od(t0) / K);
let h: Vec<f64> = (1..=12).map(|k| 10f64.powi(-k)).collect();
let names = ["fwd", "cen", "one", "sec"];
let err: Vec<Vec<f64>> = vec![
h.iter().map(|&h| ((od(t0 + h) - od(t0)) / h - d1).abs()).collect(),
h.iter().map(|&h| ((od(t0 + h) - od(t0 - h)) / (2.0 * h) - d1).abs()).collect(),
h.iter().map(|&h| ((-3.0 * od(t0) + 4.0 * od(t0 + h) - od(t0 + 2.0 * h)) / (2.0 * h) - d1).abs()).collect(),
h.iter().map(|&h| ((od(t0 + h) - 2.0 * od(t0) + od(t0 - h)) / (h * h) - d2).abs()).collect(),
];
println!(" h fwd cen one sec");
for i in 0..h.len() {
print!("{:.0e}", h[i]);
for e in &err { print!(" {:.2e}", e[i]); }
println!();
}
print!("best h:");
for (k, e) in err.iter().enumerate() {
let i = (0..h.len()).min_by(|&a, &b| e[a].partial_cmp(&e[b]).unwrap()).unwrap();
print!(" {} {:.0e}", names[k], h[i]);
}
println!();
let lh: Vec<f64> = h[..3].iter().map(|x| x.log10()).collect(); // h >= 1e-3
print!("slope: ");
for (k, e) in err.iter().enumerate() {
let le: Vec<f64> = e[..3].iter().map(|x| x.log10()).collect();
print!(" {} {:.4}", names[k], slope(&lh, &le));
}
println!();
}
// Output:
// h fwd cen one sec
// 1e-1 2.89e-3 7.04e-5 1.56e-4 5.14e-5
// 1e-2 2.95e-4 7.05e-7 1.42e-6 5.14e-7
// 1e-3 2.96e-5 7.05e-9 1.41e-8 5.21e-9
// 1e-4 2.96e-6 6.98e-11 1.41e-10 7.82e-9
// 1e-5 2.96e-7 9.32e-13 1.20e-11 9.07e-7
// 1e-6 2.96e-8 4.90e-11 3.42e-11 1.49e-4
// 1e-7 1.99e-9 5.06e-10 2.17e-9 9.25e-3
// 1e-8 3.00e-9 2.29e-10 3.00e-9 6.14e-1
// 1e-9 1.92e-8 7.47e-8 8.56e-9 1.11e2
// 1e-10 1.47e-7 4.08e-7 7.02e-7 1.11e4
// 1e-11 5.70e-6 1.47e-7 1.12e-5 1.11e6
// 1e-12 3.90e-5 1.65e-5 9.45e-5 1.11e8
// best h: fwd 1e-7 cen 1e-5 one 1e-5 sec 1e-3
// slope: fwd 0.9946 cen 2.0000 one 2.0220 sec 1.9968Best steps: \(10^{-7}\) (forward; \(\varepsilon^{1/2} = 1.5\times10^{-8}\)), \(10^{-5}\) (central and one-sided; \(\varepsilon^{1/3} = 6\times10^{-6}\)), \(10^{-3}\) (second difference; \(\varepsilon^{1/4} = 1.2\times10^{-4}\), B4(b): \(5\times10^{-4}\)). On a grid of powers of 10 the minimum can only be read to within a factor of 10, and the rounding errors are jagged; the rule of thumb is right to that precision. Slopes 1, 2, 2, 2: the orders of fact 1. The one-sided formula has twice the error of the central one (\(\tfrac{h^2}{3}\) vs \(\tfrac{h^2}{6}\)) for the same order. At \(h = 10^{-12}\) the second difference is wrong by \(10^8\).
C2.
fd_weights <- function(s, m) {
n <- length(s)
A <- outer(0:(n - 1), s, function(k, s) s^k / factorial(k))
b <- numeric(n); b[m + 1] <- 1 # pick out the m-th derivative
solve(A, b)
}
fd_weights(c(-1, 0, 1), 1)
fd_weights(c(-1, 0, 1), 2)
fd_weights(c(0, 1, 2), 1)
w5 <- fd_weights(-2:2, 1); round(w5 * 12, 10) # five-point stencil, times 12
D5 <- function(h) sum(w5 * od(3 + (-2:2) * h)) / h
e5 <- sapply(c(0.1, 0.05), D5) - gr(3)
c(e5, e5[1] / e5[2])
# Output:
# [1] -0.5 0.0 0.5
# [1] 1 -2 1
# [1] -1.5 2.0 -0.5
# [1] 1 -8 0 8 -1
# [1] -5.355997e-08 -3.336918e-09 1.605073e+01from math import factorial
def fd_weights(s, m):
s = np.asarray(s, dtype=float); n = len(s)
A = np.array([[sj**k / factorial(k) for sj in s] for k in range(n)])
b = np.zeros(n); b[m] = 1 # pick out the m-th derivative
return np.linalg.solve(A, b)
print(fd_weights([-1, 0, 1], 1))
print(fd_weights([-1, 0, 1], 2))
print(fd_weights([0, 1, 2], 1))
w5 = fd_weights(range(-2, 3), 1); print(np.round(w5 * 12, 10)) # five-point, times 12
def D5(h): return np.sum(w5 * od(3 + np.arange(-2, 3) * h)) / h
e5 = np.array([D5(0.1), D5(0.05)]) - gr(3)
print(e5, e5[0] / e5[1])
# Output:
# [-0.5 0. 0.5]
# [ 1. -2. 1.]
# [-1.5 2. -0.5]
# [ 1. -8. 0. 8. -1.]
# [-5.35599711e-08 -3.33691738e-09] 16.050733349658817// rust/examples/finite_differences_c2.rs — cargo run --example finite_differences_c2
// C2: stencil weights from a small linear system (nalgebra).
use nalgebra::{DMatrix, DVector};
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
fn factorial(k: usize) -> f64 {
(1..=k).map(|i| i as f64).product()
}
fn fd_weights(s: &[f64], m: usize) -> Vec<f64> {
let n = s.len();
let a = DMatrix::from_fn(n, n, |k, j| s[j].powi(k as i32) / factorial(k));
let mut b = DVector::zeros(n);
b[m] = 1.0; // pick out the m-th derivative
a.lu().solve(&b).unwrap().iter().cloned().collect()
}
fn main() {
println!("{:?}", fd_weights(&[-1.0, 0.0, 1.0], 1));
println!("{:?}", fd_weights(&[-1.0, 0.0, 1.0], 2));
println!("{:?}", fd_weights(&[0.0, 1.0, 2.0], 1));
let s5 = [-2.0, -1.0, 0.0, 1.0, 2.0];
let w5 = fd_weights(&s5, 1);
let w12: Vec<f64> = w5.iter().map(|w| (w * 12.0 * 1e10).round() / 1e10 + 0.0).collect();
println!("{:?}", w12); // five-point, times 12
let exact = R * od(3.0) * (1.0 - od(3.0) / K);
let d5 = |h: f64| s5.iter().zip(&w5).map(|(s, w)| w * od(3.0 + s * h)).sum::<f64>() / h;
let (e1, e2) = (d5(0.1) - exact, d5(0.05) - exact);
println!("{:e} {:e} {}", e1, e2, e1 / e2);
}
// Output:
// [-0.5, 0.0, 0.5]
// [1.0, -2.0, 1.0]
// [-1.5, 2.0, -0.5]
// [1.0, -8.0, 0.0, 8.0, -1.0]
// -5.3559971430194864e-8 -3.3369158547458255e-9 16.050740792286042The five-point weights are \((1, -8, 0, 8, -1)/12\), and halving \(h\) divides the error by 16: fourth order, \(N'(t) \approx \dfrac{N(t-2h) - 8N(t-h) + 8N(t+h) - N(t+2h)}{12h}\). (The middle weight is \(10^{-15}\) instead of 0 in R before rounding: solve works in floating point.) Note that the five-point formula at \(h = 0.1\) has error \(5.4\times10^{-8}\), the same as Richardson in B5(a): Richardson on \(D(0.2)\) and \(D(0.1)\) is this five-point formula.
C3.
richardson <- function(f, x, h0, levels = 4) {
A <- matrix(NA, levels, levels)
for (i in 1:levels) {
h <- h0 / 2^(i - 1)
A[i, 1] <- (f(x + h) - f(x - h)) / (2 * h) # central difference
}
for (j in 2:levels) for (i in j:levels) # remove the h^(2(j-1)) term
A[i, j] <- (4^(j - 1) * A[i, j - 1] - A[i - 1, j - 1]) / (4^(j - 1) - 1)
A
}
signif(richardson(od, 3, 0.4) - gr(3), 3)
signif(richardson(od, 3, 1e-4) - gr(3), 3)
numDeriv::grad(od, 3) - gr(3)
# Output:
# [,1] [,2] [,3] [,4]
# [1,] -1.12e-03 NA NA NA
# [2,] -2.82e-04 -8.68e-07 NA NA
# [3,] -7.04e-05 -5.36e-08 7.05e-10 NA
# [4,] -1.76e-05 -3.34e-09 1.13e-11 2.74e-13
# [,1] [,2] [,3] [,4]
# [1,] -6.98e-11 NA NA NA
# [2,] -1.70e-11 5.48e-13 NA NA
# [3,] -5.37e-12 -1.49e-12 -1.62e-12 NA
# [4,] -4.26e-12 -3.89e-12 -4.05e-12 -4.09e-12
# [1] 2.060019e-13def richardson(f, x, h0, levels=4):
A = np.full((levels, levels), np.nan)
for i in range(levels):
h = h0 / 2**i
A[i, 0] = (f(x + h) - f(x - h)) / (2 * h) # central difference
for j in range(1, levels): # remove the h^(2j) term
for i in range(j, levels):
A[i, j] = (4**j * A[i, j - 1] - A[i - 1, j - 1]) / (4**j - 1)
return A
np.set_printoptions(precision=2)
print(richardson(od, 3.0, 0.4) - gr(3))
print(richardson(od, 3.0, 1e-4) - gr(3))
from scipy.differentiate import derivative
print(derivative(od, 3.0).df - gr(3))
# Output:
# [[-1.12e-03 nan nan nan]
# [-2.82e-04 -8.68e-07 nan nan]
# [-7.04e-05 -5.36e-08 7.05e-10 nan]
# [-1.76e-05 -3.34e-09 1.13e-11 2.74e-13]]
# [[-6.98e-11 nan nan nan]
# [-1.70e-11 5.48e-13 nan nan]
# [-5.37e-12 -1.49e-12 -1.62e-12 nan]
# [-4.26e-12 -3.89e-12 -4.05e-12 -4.09e-12]]
# 8.243405957841787e-15// rust/examples/finite_differences_c3.rs — cargo run --example finite_differences_c3
// C3: Richardson table for the central difference (hand-written).
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
fn richardson(f: impl Fn(f64) -> f64, x: f64, h0: f64, levels: usize) -> Vec<Vec<f64>> {
let mut a = vec![vec![f64::NAN; levels]; levels];
for i in 0..levels {
let h = h0 / 2f64.powi(i as i32);
a[i][0] = (f(x + h) - f(x - h)) / (2.0 * h); // central difference
}
for j in 1..levels {
let p = 4f64.powi(j as i32); // remove the h^(2j) term
for i in j..levels {
a[i][j] = (p * a[i][j - 1] - a[i - 1][j - 1]) / (p - 1.0);
}
}
a
}
fn main() {
let exact = R * od(3.0) * (1.0 - od(3.0) / K);
for h0 in [0.4, 1e-4] {
for row in richardson(od, 3.0, h0, 4) {
let cells: Vec<String> = row.iter()
.map(|v| if v.is_nan() { " NA".into() } else { format!("{:>9.2e}", v - exact) })
.collect();
println!("{}", cells.join(" "));
}
println!();
}
}
// Output:
// -1.12e-3 NA NA NA
// -2.82e-4 -8.68e-7 NA NA
// -7.04e-5 -5.36e-8 7.05e-10 NA
// -1.76e-5 -3.34e-9 1.13e-11 2.74e-13
//
// -6.98e-11 NA NA NA
// -1.70e-11 5.48e-13 NA NA
// -5.37e-12 -1.49e-12 -1.62e-12 NA
// -4.26e-12 -3.89e-12 -4.05e-12 -4.09e-12From \(h_0 = 0.4\) each column gains accuracy: the corner is \(2.7\times10^{-13}\), using 8 function values. From \(h_0 = 10^{-4}\) the first column is already in the rounding regime (around \(10^{-11}\)), the error is no longer \(c_2h^2\), and extrapolation cannot improve it: stuck at \(4\times10^{-12}\). Richardson works best with a large starting step, which is why numDeriv::grad starts at \(10^{-4}|x|\) and not at \(10^{-8}\). (numDeriv::grad: \(2.1\times10^{-13}\); scipy.differentiate.derivative: \(8\times10^{-15}\) after 11 evaluations.)
C4.
dt <- 1/6; n <- length(y)
i <- 2:(n - 1)
cen <- (y[i + 1] - y[i - 1]) / (2 * dt)
c(rms = sqrt(mean((cen - gr(t[i]))^2)), min = min(cen), max = max(cen))
rms <- sapply(1:8, function(k) {
j <- (k + 1):(n - k)
d <- (y[j + k] - y[j - k]) / (2 * k * dt)
sqrt(mean((d - gr(t[j]))^2))
})
print(data.frame(k = 1:8, h_min = 10 * (1:8), rms = signif(rms, 3)))
k <- which.min(rms); j <- (k + 1):(n - k)
d <- (y[j + k] - y[j - k]) / (2 * k * dt)
c(max = max(d), at = t[j][which.max(d)])
# Output:
# rms min max
# 0.02030602 -0.03300000 0.27000000
# k h_min rms
# 1 1 10 0.02030
# 2 2 20 0.00916
# 3 3 30 0.00652
# 4 4 40 0.00528
# 5 5 50 0.00576
# 6 6 60 0.00685
# 7 7 70 0.00864
# 8 8 80 0.01080
# max at
# 0.233250 4.333333dt = 1 / 6; n = len(y)
cen = (y[2:] - y[:-2]) / (2 * dt)
print(f"rms {np.sqrt(np.mean((cen - gr(t[1:-1]))**2)):.6f} min {cen.min():.3f} max {cen.max():.3f}")
def wide(k): # half-width k*dt, points k..n-k-1
return (y[2 * k:] - y[:-2 * k]) / (2 * k * dt), t[k:n - k]
rms = []
for k in range(1, 9):
d, tk = wide(k)
rms.append(np.sqrt(np.mean((d - gr(tk))**2)))
print(k, 10 * k, f"{rms[-1]:.3g}")
k = int(np.argmin(rms)) + 1
d, tk = wide(k)
print(f"max {d.max():.5f} at {tk[np.argmax(d)]:.4f} h")
# Output:
# rms 0.020306 min -0.033 max 0.270
# 1 10 0.0203
# 2 20 0.00916
# 3 30 0.00652
# 4 40 0.00528
# 5 50 0.00576
# 6 60 0.00685
# 7 70 0.00864
# 8 80 0.0108
# max 0.23325 at 4.3333 h// rust/examples/finite_differences_c4.rs — cargo run --example finite_differences_c4
// C4: growth rate from noisy plate-reader data, central differences of width k.
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
const Y: [f64; 61] = [
0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203];
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
fn gr(t: f64) -> f64 {
R * od(t) * (1.0 - od(t) / K)
}
// central difference with half-width k*dt: (times, estimates)
fn wide(k: usize, dt: f64) -> (Vec<f64>, Vec<f64>) {
(k..Y.len() - k)
.map(|i| (i as f64 * dt, (Y[i + k] - Y[i - k]) / (2.0 * k as f64 * dt)))
.unzip()
}
fn rms(t: &[f64], d: &[f64]) -> f64 {
(t.iter().zip(d).map(|(t, d)| (d - gr(*t)).powi(2)).sum::<f64>() / t.len() as f64).sqrt()
}
fn main() {
let dt = 1.0 / 6.0;
let (t1, d1) = wide(1, dt);
let min = d1.iter().cloned().fold(f64::INFINITY, f64::min);
let max = d1.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
println!("rms {:.6} min {:.3} max {:.3}", rms(&t1, &d1), min, max);
let r: Vec<f64> = (1..=8).map(|k| { let (t, d) = wide(k, dt); rms(&t, &d) }).collect();
for k in 1..=8 { println!("{} {} {:.3e}", k, 10 * k, r[k - 1]); }
let kbest = 1 + (0..8).min_by(|&a, &b| r[a].partial_cmp(&r[b]).unwrap()).unwrap();
let (t, d) = wide(kbest, dt);
let imax = (0..d.len()).max_by(|&a, &b| d[a].partial_cmp(&d[b]).unwrap()).unwrap();
println!("max {:.5} at {:.4} h", d[imax], t[imax]);
}
// Output:
// rms 0.020306 min -0.033 max 0.270
// 1 10 2.031e-2
// 2 20 9.159e-3
// 3 30 6.524e-3
// 4 40 5.283e-3
// 5 50 5.765e-3
// 6 60 6.853e-3
// 7 70 8.637e-3
// 8 80 1.080e-2
// max 0.23325 at 4.3333 h- rms error 0.0203 OD/h, as B6(a) predicts (0.0212); estimates range from \(-0.033\) (a negative growth rate in the stationary phase) to \(0.270\) (the true maximum is 0.240).
- The error falls until \(k = 4\) (40 min, rms 0.0053, four times better) and then rises again as truncation takes over: the V of the lecture, with the noise in place of rounding. B4(c) predicted 30 min at the inflection point.
- Maximum 0.233 OD/h at 4.33 h (true 0.240 at 3.92 h). The wide stencil flattens the peak a little, and the time of the maximum is only known to about \(\pm\) half an hour: the curve is flat near its top, so noise moves the arg max easily.
C5.
dt <- 1/6; n <- length(y)
local_slope <- function(y, m, dt) {
j <- -m:m
i <- (m + 1):(length(y) - m)
sapply(i, function(i) sum(j * y[i + j]) / (dt * sum(j^2)))
}
rms <- sapply(1:8, function(m) {
i <- (m + 1):(n - m)
sqrt(mean((local_slope(y, m, dt) - gr(t[i]))^2))
})
print(data.frame(m = 1:8, rms = signif(rms, 3)))
m <- which.min(rms); i <- (m + 1):(n - m)
d <- local_slope(y, m, dt)
c(m = m, max = max(d), at = t[i][which.max(d)])
# Output:
# m rms
# 1 1 0.02030
# 2 2 0.00882
# 3 3 0.00527
# 4 4 0.00405
# 5 5 0.00405
# 6 6 0.00469
# 7 7 0.00590
# 8 8 0.00742
# m max at
# 4.000000 0.234400 4.333333dt = 1 / 6; n = len(y)
def local_slope(y, m, dt):
j = np.arange(-m, m + 1)
return np.array([np.sum(j * y[i + j]) for i in range(m, len(y) - m)]) / (dt * np.sum(j**2))
rms = []
for m in range(1, 9):
d = local_slope(y, m, dt)
rms.append(np.sqrt(np.mean((d - gr(t[m:n - m]))**2)))
print(m, f"{rms[-1]:.3g}")
m = int(np.argmin(rms)) + 1
d = local_slope(y, m, dt)
print(f"m {m} max {d.max():.4f} at {t[m:n - m][np.argmax(d)]:.4f} h")
# Output:
# 1 0.0203
# 2 0.00882
# 3 0.00527
# 4 0.00405
# 5 0.00405
# 6 0.00469
# 7 0.0059
# 8 0.00742
# m 4 max 0.2344 at 4.3333 h// rust/examples/finite_differences_c5.rs — cargo run --example finite_differences_c5
// C5: local least-squares slope over a window of 2m+1 points.
const K: f64 = 1.2;
const N0: f64 = 0.05;
const R: f64 = 0.8;
const Y: [f64; 61] = [
0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203];
fn od(t: f64) -> f64 {
K / (1.0 + (K / N0 - 1.0) * (-R * t).exp())
}
fn gr(t: f64) -> f64 {
R * od(t) * (1.0 - od(t) / K)
}
// slope at points m..n-m-1: sum_j j*y[i+j] / (dt * sum_j j^2)
fn local_slope(y: &[f64], m: usize, dt: f64) -> Vec<f64> {
let m = m as i64;
let sjj: f64 = (-m..=m).map(|j| (j * j) as f64).sum();
(m..y.len() as i64 - m)
.map(|i| (-m..=m).map(|j| j as f64 * y[(i + j) as usize]).sum::<f64>() / (dt * sjj))
.collect()
}
fn main() {
let dt = 1.0 / 6.0;
let mut rms = Vec::new();
for m in 1..=8 {
let d = local_slope(&Y, m, dt);
let ss: f64 = d.iter().enumerate()
.map(|(k, d)| (d - gr((k + m) as f64 * dt)).powi(2)).sum();
rms.push((ss / d.len() as f64).sqrt());
println!("{} {:.3e}", m, rms[m - 1]);
}
let m = 1 + (0..8).min_by(|&a, &b| rms[a].partial_cmp(&rms[b]).unwrap()).unwrap();
let d = local_slope(&Y, m, dt);
let imax = (0..d.len()).max_by(|&a, &b| d[a].partial_cmp(&d[b]).unwrap()).unwrap();
println!("m {} max {:.4} at {:.4} h", m, d[imax], (imax + m) as f64 * dt);
}
// Output:
// 1 2.031e-2
// 2 8.815e-3
// 3 5.271e-3
// 4 4.052e-3
// 5 4.054e-3
// 6 4.687e-3
// 7 5.905e-3
// 8 7.417e-3
// m 4 max 0.2344 at 4.3333 h\(m = 4\) (or 5): rms 0.0041, better than the plain central difference of the same half-width (0.0053). The local fit uses all \(2m+1\) points, not just the two outermost ones, so it averages more noise. (It is a weighted average of the central differences with \(k = 1, \dots, m\), with weights \(\propto k^2\).) Maximum 0.234 at 4.33 h. This is a Savitzky–Golay derivative filter of degree 1; the smoothing spline of the lecture (rms 0.0047) has the advantage of giving values at the ends too.
C6.
sigma <- 0.005
logistic <- function(t, r, K, N0) K / (1 + (K / N0 - 1) * exp(-r * t))
loglik <- function(th) -sum((y - logistic(t, th[1], th[2], th[3]))^2) / (2 * sigma^2)
grad_exact <- function(th) {
r <- th[1]; K <- th[2]; N0 <- th[3]
E <- exp(-r * t); D <- 1 + (K / N0 - 1) * E; N <- K / D
dN <- cbind(t * N * (1 - N / K), # dN/dr
1 / D - K * E / (N0 * D^2), # dN/dK
K^2 * E / (N0^2 * D^2)) # dN/dN0
colSums((y - N) / sigma^2 * dN)
}
fd_grad <- function(f, x, h, central = TRUE) sapply(seq_along(x), function(j) {
e <- numeric(length(x)); e[j] <- h[j]
if (central) (f(x + e) - f(x - e)) / (2 * h[j]) else (f(x + e) - f(x)) / h[j]
})
th <- c(0.75, 1.15, 0.06)
g <- grad_exact(th)
rel <- function(a) signif(abs(a - g) / abs(g), 3)
rbind(fwd = rel(fd_grad(loglik, th, 1e-8 * pmax(abs(th), 1), central = FALSE)),
cen = rel(fd_grad(loglik, th, 6e-6 * pmax(abs(th), 1))),
numDeriv = rel(numDeriv::grad(loglik, th)))
# (b) at the maximum
mle <- c(0.79542677, 1.20245707, 0.050760766)
rbind(exact = grad_exact(mle),
abs_1e3 = fd_grad(loglik, mle, rep(1e-3, 3)),
rel_1e3 = fd_grad(loglik, mle, 1e-3 * abs(mle)),
rel_6e6 = fd_grad(loglik, mle, 6e-6 * abs(mle)))
# (c) a bug: dN/dr without the factor t
grad_bug <- function(th) {
r <- th[1]; K <- th[2]; N0 <- th[3]
E <- exp(-r * t); D <- 1 + (K / N0 - 1) * E; N <- K / D
dN <- cbind(N * (1 - N / K), 1 / D - K * E / (N0 * D^2), K^2 * E / (N0^2 * D^2))
colSums((y - N) / sigma^2 * dN)
}
fd <- fd_grad(loglik, th, 6e-6 * pmax(abs(th), 1))
signif(abs(grad_bug(th) - fd) / abs(fd), 3)
# Output:
# [,1] [,2] [,3]
# fwd 1.59e-07 8.10e-08 1.14e-06
# cen 1.12e-09 6.26e-11 6.39e-08
# numDeriv 2.52e-12 9.15e-12 1.43e-12
# [,1] [,2] [,3]
# exact -0.003733883 -0.00442755 -0.01428785
# abs_1e3 1.184361910 0.05727214 289.62997944
# rel_1e3 0.747978434 0.08478422 0.73179928
# rel_6e6 -0.003706832 -0.00442434 -0.01426078
# [1] 8.53e-01 6.26e-11 6.39e-08from scipy.optimize import approx_fprime
sigma = 0.005
def logistic(t, r, K, N0): return K / (1 + (K / N0 - 1) * np.exp(-r * t))
def loglik(th): return -np.sum((y - logistic(t, *th))**2) / (2 * sigma**2)
def grad_exact(th, bug=False):
r, K, N0 = th
E = np.exp(-r * t); D = 1 + (K / N0 - 1) * E; N = K / D
dN = np.column_stack([(1 if bug else t) * N * (1 - N / K), # dN/dr
1 / D - K * E / (N0 * D**2), # dN/dK
K**2 * E / (N0**2 * D**2)]) # dN/dN0
return ((y - N) / sigma**2) @ dN
def fd_grad(f, x, h, central=True):
g = np.zeros(len(x))
for j in range(len(x)):
e = np.zeros(len(x)); e[j] = h[j]
g[j] = (f(x + e) - f(x - e)) / (2 * h[j]) if central else (f(x + e) - f(x)) / h[j]
return g
th = np.array([0.75, 1.15, 0.06])
g = grad_exact(th)
def rel(a): return np.abs(a - g) / np.abs(g)
np.set_printoptions(precision=3)
print("fwd ", rel(fd_grad(loglik, th, 1e-8 * np.maximum(np.abs(th), 1), central=False)))
print("cen ", rel(fd_grad(loglik, th, 6e-6 * np.maximum(np.abs(th), 1))))
print("approx_fprime", rel(approx_fprime(th, loglik))) # forward, h = sqrt(eps)
mle = np.array([0.79542677, 1.20245707, 0.050760766]) # (b)
np.set_printoptions(precision=6, suppress=True)
print("exact ", grad_exact(mle))
print("abs_1e3", fd_grad(loglik, mle, np.full(3, 1e-3)))
print("rel_1e3", fd_grad(loglik, mle, 1e-3 * np.abs(mle)))
print("rel_6e6", fd_grad(loglik, mle, 6e-6 * np.abs(mle)))
fd = fd_grad(loglik, th, 6e-6 * np.maximum(np.abs(th), 1)) # (c)
np.set_printoptions(precision=3, suppress=False)
print(np.abs(grad_exact(th, bug=True) - fd) / np.abs(fd))
# Output:
# fwd [1.608e-07 8.204e-08 1.139e-06]
# cen [1.119e-09 6.201e-11 6.390e-08]
# approx_fprime [2.457e-07 1.145e-07 1.697e-06]
# exact [-0.003734 -0.004428 -0.014288]
# abs_1e3 [ 1.184362 0.057272 289.629979]
# rel_1e3 [0.747978 0.084784 0.731799]
# rel_6e6 [-0.003707 -0.004424 -0.014261]
# [8.532e-01 6.201e-11 6.390e-08]// rust/examples/finite_differences_c6.rs — cargo run --example finite_differences_c6
// C6: gradient of a log-likelihood by finite differences, against the exact one.
const SIGMA: f64 = 0.005;
const Y: [f64; 61] = [
0.047, 0.058, 0.060, 0.081, 0.084, 0.090, 0.108, 0.123, 0.137, 0.150,
0.177, 0.192, 0.210, 0.226, 0.269, 0.292, 0.322, 0.359, 0.393, 0.428,
0.466, 0.504, 0.540, 0.569, 0.622, 0.659, 0.698, 0.730, 0.772, 0.812,
0.851, 0.876, 0.909, 0.935, 0.955, 0.985, 1.007, 1.029, 1.054, 1.069,
1.079, 1.092, 1.109, 1.120, 1.123, 1.132, 1.145, 1.154, 1.155, 1.166,
1.168, 1.167, 1.175, 1.171, 1.187, 1.192, 1.183, 1.181, 1.191, 1.189,
1.203];
fn t(i: usize) -> f64 { i as f64 / 6.0 }
fn loglik(th: &[f64]) -> f64 {
let (r, k, n0) = (th[0], th[1], th[2]);
-(0..61).map(|i| (Y[i] - k / (1.0 + (k / n0 - 1.0) * (-r * t(i)).exp())).powi(2))
.sum::<f64>() / (2.0 * SIGMA * SIGMA)
}
fn grad_exact(th: &[f64], bug: bool) -> [f64; 3] {
let (r, k, n0) = (th[0], th[1], th[2]);
let mut g = [0.0; 3];
for i in 0..61 {
let e = (-r * t(i)).exp();
let d = 1.0 + (k / n0 - 1.0) * e;
let n = k / d;
let w = (Y[i] - n) / (SIGMA * SIGMA);
let tr = if bug { 1.0 } else { t(i) };
g[0] += w * tr * n * (1.0 - n / k); // dN/dr
g[1] += w * (1.0 / d - k * e / (n0 * d * d)); // dN/dK
g[2] += w * k * k * e / (n0 * n0 * d * d); // dN/dN0
}
g
}
fn fd_grad(f: fn(&[f64]) -> f64, x: &[f64], h: &[f64], central: bool) -> [f64; 3] {
let mut g = [0.0; 3];
for j in 0..3 {
let (mut xp, mut xm) = (x.to_vec(), x.to_vec());
xp[j] += h[j];
xm[j] -= h[j];
g[j] = if central { (f(&xp) - f(&xm)) / (2.0 * h[j]) } else { (f(&xp) - f(x)) / h[j] };
}
g
}
fn main() {
let th: [f64; 3] = [0.75, 1.15, 0.06];
let g = grad_exact(&th, false);
let rel = |a: [f64; 3]| -> Vec<String> {
(0..3).map(|j| format!("{:.3e}", (a[j] - g[j]).abs() / g[j].abs())).collect()
};
let hrel = |c: f64| -> Vec<f64> { th.iter().map(|x| c * x.abs().max(1.0)).collect() };
println!("fwd {:?}", rel(fd_grad(loglik, &th, &hrel(1e-8), false)));
println!("cen {:?}", rel(fd_grad(loglik, &th, &hrel(6e-6), true)));
// (b) at the maximum
let mle: [f64; 3] = [0.79542677, 1.20245707, 0.050760766];
let scaled = |c: f64| -> Vec<f64> { mle.iter().map(|x| c * x.abs()).collect() };
println!("exact {:.6?}", grad_exact(&mle, false));
println!("abs_1e3 {:.6?}", fd_grad(loglik, &mle, &[1e-3; 3], true));
println!("rel_1e3 {:.6?}", fd_grad(loglik, &mle, &scaled(1e-3), true));
println!("rel_6e6 {:.6?}", fd_grad(loglik, &mle, &scaled(6e-6), true));
// (c) a bug: dN/dr without the factor t
let fd = fd_grad(loglik, &th, &hrel(6e-6), true);
let gb = grad_exact(&th, true);
let rb: Vec<String> = (0..3).map(|j| format!("{:.3e}", (gb[j] - fd[j]).abs() / fd[j].abs())).collect();
println!("bug {:?}", rb);
}
// Output:
// fwd ["1.618e-7", "8.169e-8", "1.139e-6"]
// cen ["1.115e-9", "6.201e-11", "6.390e-8"]
// exact [-0.003734, -0.004428, -0.014288]
// abs_1e3 [1.184362, 0.057272, 289.629979]
// rel_1e3 [0.747978, 0.084784, 0.731799]
// rel_6e6 [-0.003707, -0.004424, -0.014261]
// bug ["8.532e-1", "6.201e-11", "6.390e-8"]- Forward: \(10^{-7}\) to \(10^{-6}\) relative error (about half the digits). Central: \(10^{-11}\) to \(10^{-7}\).
numDeriv::grad: \(10^{-12}\).approx_fprimeis a forward difference with \(h = \sqrt\varepsilon\) (not scaled to \(|\theta_j|\)), so it is similar to our forward difference. R, Python and Rust differ in the second digit of the forward errors:np.arange(61) / 6andseq(0, 10, by = 1/6)give times that differ in the last bit, and the sums are added in a different order. The forward difference sits near the bottom of its V, where such rounding differences are amplified; the central errors agree. - The exact gradient at the maximum is \((-0.004, -0.004, -0.014)\), numerically zero (the gradient at \(\theta\) in (a) was \(10^4\)–\(10^5\)). With an absolute step of \(10^{-3}\) the \(N_0\) component is 290: the step is 2 % of \(N_0 = 0.05\), far into the truncation regime of a strongly curved direction. The \(r\) component (1.2) is also off. An optimiser that sees this gradient stops before the true maximum, as on the lecture slide. A relative step \(10^{-3}|\theta_j|\) gives errors below 1, and \(6\times10^{-6}|\theta_j|\) agrees with the exact gradient to two digits even here, where the gradient is 0 up to rounding.
- The \(r\) component differs by 85 %; the others agree to \(10^{-8}\)–\(10^{-11}\). A component with relative difference of order 1 (rather than \(10^{-6}\)) points straight at the wrong partial derivative. This gradient check is what to run before trusting any hand-written (or AD) gradient.
Where this leads
- Numerical integration (next unit): integration averages noise instead of amplifying it, and Richardson extrapolation of the trapezoid rule becomes Romberg integration.
- Splines (Part 6): the smoothing spline used on the lecture slide to differentiate noisy data, and how its smoothness is chosen.
- Gradient descent, Newton and quasi-Newton and Nonlinear least squares and ODE fitting (Part 10): optimisers that use the gradients of C6, and the methods for fitting a model (there a drug-concentration model; a growth model works the same way) instead of differentiating the data. Identifiability and uncertainty of fitted parameters uses the Hessian, again by finite differences.
- The diffusion (heat) equation by finite differences (Part 11): the \((1, -2, 1)/h^2\) stencil of B2 becomes the diffusion term on a spatial grid, with the same \(O(h^2)\) error.