Exercise: Newton for systems of equations
Goal
By the end of this exercise you should be able to:
- compute partial derivatives of a function of two variables, and check them with a difference quotient,
- write down the Jacobian of a small system and explain what each entry means for the biology,
- do a Newton step for a system by hand (one \(2\times2\) linear solve) and in code (
solve(J, -F)), - recognise quadratic convergence in a table of errors,
- build a finite-difference Jacobian and explain how the step \(h\) affects Newton’s convergence,
- use a library routine (
rootSolve::multirootin R,scipy.optimize.rootin Python) and check its answer, - find all steady states of the genetic toggle switch with many starts, and spot when Newton fails (nearly singular Jacobian, negative concentrations,
NaN, a root you did not want).
The by-hand part needs pen, paper and a calculator. The code part checks your hand answers and then explores where only code works.
Background
The toggle switch. Two genes repress each other. With concentrations \(u\), \(v\) (in units of the repression threshold) and time in units of the protein lifetime,
\[\frac{du}{dt} = \frac{\alpha}{1 + v^{n}} - u, \qquad \frac{dv}{dt} = \frac{\alpha}{1 + u^{n}} - v,\]
with promoter strength \(\alpha = 3\) and Hill coefficient \(n = 2\) unless stated otherwise. A steady state is a root of \(\mathbf F(\mathbf x) = \mathbf 0\), with \(\mathbf x = (u, v)\) and
\[F_1(u, v) = \frac{\alpha}{1 + v^{n}} - u, \qquad F_2(u, v) = \frac{\alpha}{1 + u^{n}} - v.\]
Facts used below:
- Partial derivative. \(\partial F_i / \partial x_j\) is the ordinary derivative of \(F_i\) with respect to \(x_j\), with every other variable held fixed at its value. Check: \(\big(F_i(\mathbf x + h\,\mathbf e_j) - F_i(\mathbf x)\big)/h\) for small \(h\), where \(\mathbf e_j\) moves only \(x_j\).
- Jacobian. \(J_{ij} = \partial F_i / \partial x_j\): row = equation, column = variable. For the toggle switch \[J(u, v) = \begin{pmatrix} -1 & -\dfrac{\alpha n v^{n-1}}{(1+v^n)^2} \\[6pt] -\dfrac{\alpha n u^{n-1}}{(1+u^n)^2} & -1 \end{pmatrix}.\]
- Linear approximation. \(\mathbf F(\mathbf x + \boldsymbol\delta) \approx \mathbf F(\mathbf x) + J(\mathbf x)\,\boldsymbol\delta\), with an error of order \(\|\boldsymbol\delta\|^2\).
- Newton step. Solve \(J(\mathbf x_k)\,\boldsymbol\delta = -\mathbf F(\mathbf x_k)\), then \(\mathbf x_{k+1} = \mathbf x_k + \boldsymbol\delta\). Near a root with a non-singular Jacobian, convergence is quadratic: \(e_{k+1} \approx C e_k^2\).
- Length of a vector (Euclidean norm): \(\|\mathbf a\| = \sqrt{a_1^2 + a_2^2}\). Used for the residual \(\|\mathbf F\|\), the step \(\|\boldsymbol\delta\|\) and the error \(\|\mathbf x_k - \mathbf x^*\|\).
- Finite-difference Jacobian. Column \(j\) is \(\big(\mathbf F(\mathbf x + h_j \mathbf e_j) - \mathbf F(\mathbf x)\big)/h_j\) with \(h_j = \sqrt{\varepsilon}\,\max(|x_j|, 1)\), \(\sqrt\varepsilon \approx 1.5\times10^{-8}\). About 8 correct digits; \(n + 1\) evaluations of \(\mathbf F\).
- Library routines. R:
rootSolve::multiroot(Newton with a finite-difference Jacobian unless you passjacfunc). Python:scipy.optimize.root(default method"hybr", Powell’s hybrid method from MINPACK) or the olderscipy.optimize.fsolve. Rust: none in our crate list, so we hand-write Newton withnalgebra’s LU solve.
The model, its Jacobian and one Newton step in each language (R: solve; Python: np.linalg.solve):
alpha <- 3; n <- 2
F <- function(x) { # x = c(u, v); returns c(F1, F2)
u <- x[1]; v <- x[2]
c(alpha / (1 + v^n) - u,
alpha / (1 + u^n) - v)
}
J <- function(x) { # row i = equation i, column j = variable j
u <- x[1]; v <- x[2]
matrix(c(-1, -alpha * n * v^(n - 1) / (1 + v^n)^2,
-alpha * n * u^(n - 1) / (1 + u^n)^2, -1),
nrow = 2, byrow = TRUE)
}
x0 <- c(3, 0.5)
F(x0)
# [1] -0.6 -0.2
J(x0)
# [,1] [,2]
# [1,] -1.00 -1.92
# [2,] -0.18 -1.00
delta <- solve(J(x0), -F(x0)) # one Newton step = one linear solve
x0 + delta
# [1] 2.6699267 0.3594132import numpy as np
alpha, n = 3.0, 2.0
def F(x): # x = [u, v]; returns [F1, F2]
u, v = x
return np.array([alpha / (1 + v**n) - u,
alpha / (1 + u**n) - v])
def J(x): # row i = equation i, column j = variable j
u, v = x
return np.array([[-1, -alpha * n * v**(n - 1) / (1 + v**n)**2],
[-alpha * n * u**(n - 1) / (1 + u**n)**2, -1]])
x0 = np.array([3.0, 0.5])
print(F(x0))
# [-0.6 -0.2]
print(J(x0))
# [[-1. -1.92]
# [-0.18 -1. ]]
delta = np.linalg.solve(J(x0), -F(x0)) # one Newton step = one linear solve
print(x0 + delta)
# [2.66992665 0.3594132 ]// rust/examples/newton_systems_background.rs — cargo run --example newton_systems_background
// Background: the toggle switch F, its Jacobian J, and one Newton step.
use nalgebra::{Matrix2, Vector2};
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
// x = (u, v); returns (F1, F2)
fn f(x: &Vector2<f64>) -> Vector2<f64> {
let (u, v) = (x[0], x[1]);
Vector2::new(ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v)
}
// row i = equation i, column j = variable j
fn jac(x: &Vector2<f64>) -> Matrix2<f64> {
let (u, v) = (x[0], x[1]);
Matrix2::new(-1.0, -ALPHA * N * v.powf(N - 1.0) / (1.0 + v.powf(N)).powi(2),
-ALPHA * N * u.powf(N - 1.0) / (1.0 + u.powf(N)).powi(2), -1.0)
}
fn main() {
let x0 = Vector2::new(3.0, 0.5);
println!("{:?}", f(&x0).as_slice());
println!("{}", jac(&x0)); // nalgebra prints matrices as a box
// one Newton step = one linear solve (LU); solve() returns None if J is singular
let delta = jac(&x0).lu().solve(&(-f(&x0))).expect("singular Jacobian");
println!("{:?}", (x0 + delta).as_slice());
}
// Output:
// [-0.6000000000000001, -0.2]
//
// ┌ ┐
// │ -1 -1.92 │
// │ -0.18 -1 │
// └ ┘
//
//
// [2.6699266503667483, 0.3594132029339854]Rust prints the shortest decimal that identifies a double, so \(2.4 - 3\) shows as -0.6000000000000001 where R and numpy round to 7 or 8 digits; the values are the same.
By hand
B1. Partial derivatives. (a) \(g(u, v) = u^2 v + 3v\). Compute \(\partial g/\partial u\) and \(\partial g/\partial v\), and evaluate both at \((u, v) = (1, 2)\). (b) An enzyme makes product at rate \(r(S, E) = \dfrac{k\,E\,S}{K + S}\) (Michaelis–Menten, with enzyme concentration \(E\) and substrate \(S\)). With \(k = 2\) and \(K = 1\), compute \(\partial r/\partial E\) and \(\partial r/\partial S\) at \(S = 1\), \(E = 0.5\). Say in words what each number means. (c) Check \(\partial r/\partial S\) from (b) with a difference quotient, \(h = 0.01\).
B2. The Jacobian of the toggle switch. (a) Derive the four entries of \(J\) for general \(\alpha\) and \(n\) (Fact 2) yourself, using the chain rule on \(\alpha(1 + v^n)^{-1}\). (b) Evaluate \(J\) at \((u, v) = (1, 2)\) for \(\alpha = 3\), \(n = 2\). (c) Which entries describe degradation, and which repression? Why is \(|\partial F_2/\partial u|\) at \((1, 2)\) larger than \(|\partial F_1/\partial v|\)? (d) Evaluate \(J\) and \(\det J\) at the middle steady state \(u = v = 1.2134\).
B3. The linear approximation. At \(\mathbf x = (1, 2)\), compute \(\mathbf F(\mathbf x)\). Use \(J\) from B2(b) to predict \(\mathbf F(1.1, 1.9)\), then compute the true value. How close is the prediction?
B4. Two Newton steps. Start at \(\mathbf x_0 = (3, 0)\), with \(\alpha = 3\), \(n = 2\). (a) Compute \(\mathbf F(\mathbf x_0)\) and \(J(\mathbf x_0)\). Why is this first step especially easy? (b) Solve \(J\boldsymbol\delta = -\mathbf F\) and give \(\mathbf x_1\). (c) Do a second step from \(\mathbf x_1\) (keep 4–5 significant digits). Compare \(\mathbf x_2\) with the steady state \((2.6180, 0.3820)\).
B5. All steady states, exactly. For the toggle switch with \(n = 2\): (a) Write the two steady-state equations as \(u(1 + v^2) = \alpha\) and \(v(1 + u^2) = \alpha\). Subtract them and show that \((u - v)(1 - uv) = 0\). (b) Case \(u = v\): show that \(u^3 + u - \alpha = 0\). For \(\alpha = 3\), find the root with two Newton steps from \(u_0 = 1\) (one variable). (c) Case \(uv = 1\): show that \(u + v = \alpha\). Find \(u\) and \(v\) for \(\alpha = 3\) exactly. (You need \(t^2 - \alpha t + 1 = 0\).) (d) For which \(\alpha\) does case (c) give real, positive solutions? What does that mean for the switch?
B6. A linear system. Suppose \(\mathbf F(\mathbf x) = A\mathbf x - \mathbf b\) with a fixed invertible matrix \(A\). What is \(J\)? Show that Newton reaches the exact root in one step, from any start.
B7. A finite-difference Jacobian by hand. At \(\mathbf x = (3, 0.5)\) use \(h = 0.01\) (not scaled). (a) Compute column 2: \(\big(\mathbf F(3, 0.51) - \mathbf F(3, 0.5)\big)/0.01\). Compare with the exact column \((-1.92, -1)\). (b) Compute column 1 the same way and compare with \((-1, -0.18)\). (c) How many evaluations of \(\mathbf F\) did the whole Jacobian cost? How many for a network of 100 genes?
B8. Symmetry and cost. (a) Suppose \(u_0 = v_0\). Show that \(F_1 = F_2\) and that \(J\) is symmetric with equal diagonal entries. Conclude that \(\delta_u = \delta_v\), so every Newton iterate stays on the line \(u = v\). Which steady state can Newton then find? (b) Solving a dense \(n\times n\) system costs about \(\tfrac23 n^3\) operations. At \(10^9\) operations per second, how long does one Newton step take for \(n = 2\), \(1000\) and \(20\,000\) genes? With a finite-difference Jacobian and an \(\mathbf F\) costing \(10n\) operations, how much does building the Jacobian cost in comparison?
In code
The solutions build on each other: the Background defines F and J, C1 defines fd_jacobian, C2 defines newton_sys and the exact root xstar. Each Rust file is a complete program.
C1. Check the Jacobian. Write F and J (Background) and a function fd_jacobian(F, x, h) that returns the finite-difference Jacobian (Fact 6). Check B2(b), and compare J(x) with fd_jacobian(F, x) at \((3, 0.5)\), \((1, 2)\), \((1.2, 1.2)\) and \((0.1, 4)\). What size of difference do you expect? Also compare with a library routine: R numDeriv::jacobian, Python scipy.optimize.approx_fprime.
C2. Newton for the toggle switch. Write newton_sys(F, J, x0, tol, maxit) that returns all iterates (one per row). Check your B4 answers with a start at \((3, 0)\). Then start at \((3, 0.5)\): print the error \(\|\mathbf x_k - \mathbf x^*\|\) (use the exact root from B5) and the residual \(\|\mathbf F(\mathbf x_k)\|\) per step, and the ratios \(e_{k+1}/e_k^2\). Is the convergence quadratic?
C3. All steady states from many starts. Run Newton from a \(10\times10\) grid of starts with \(u_0, v_0 \in \{0.2, 0.6, \dots, 3.8\}\). Collect the distinct roots (round to 6 decimals). What fraction of starts goes to each? Check the residual of every run. Compare with the basin picture in the lecture.
C4. A finite-difference Jacobian inside Newton. Run Newton from \((3, 0.5)\) with fd_jacobian in place of J, for \(h = \sqrt\varepsilon\), \(10^{-4}\), \(10^{-2}\) and \(0.3\). Print the number of steps and the first five errors. What happens to the convergence when \(h\) is large?
C5. The library routine. Solve the same problem with multiroot (R) or scipy.optimize.root (Python), first with the default settings and then with your J and a tighter tolerance. How large are the residual and the error at the default settings? Do the starts \((0.5, 3)\), \((1, 1)\) and \((1, 0.2)\) give the same roots as your Newton? (Rust: no library, so count how many evaluations of \(\mathbf F\) your Newton with a finite-difference Jacobian needs.)
C6. Failure: a nearly singular Jacobian. (a) Run Newton from \((1.9, 0.5)\) and from \((2.0, 0.55)\). For each, print \(\det J(\mathbf x_0)\) (R det, Python np.linalg.det), the length of the first step, the smallest \(u\) or \(v\) along the way, and where it ends. (b) Set the Hill coefficient to \(n = 2.5\) and take two plain Newton steps from \((2, 0.5)\). What happens, and why? (c) Write a damped Newton: after computing \(\boldsymbol\delta\), try \(t = 1, \tfrac12, \tfrac14, \dots\) and accept \(\mathbf x + t\boldsymbol\delta\) as soon as all entries are \(\ge 0\) and \(\|\mathbf F\|\) has not grown. Does it solve (b)?
C7. When is the switch bistable? For \(\alpha = 1, 1.5, 2, \dots, 5\), run Newton from an \(8\times 8\) grid of starts in \([0.25, 5]^2\) and count the distinct roots with residual below \(10^{-10}\). Also count the runs that hit maxit = 50. Compare with B5(d) and the formula \(u = (\alpha + \sqrt{\alpha^2 - 4})/2\) for the “U on” state. What goes wrong at \(\alpha = 2\)?
Explore
The demo below runs Newton on the toggle switch in your browser. The plot shows the \((u, v)\) plane with the two nullclines \(F_1 = 0\) (blue) and \(F_2 = 0\) (red); the steady states are where they cross (green: U high, white: middle, purple: V high). Click or drag in the plot to move the start \(\mathbf x_0\) (orange). The thin dashed grey line is the whole Newton path; the step buttons walk along it. At the current iterate \(\mathbf x_k\) the two dashed coloured lines are the linearised nullclines, \(F_i(\mathbf x_k) + J_i(\mathbf x_k)\,\boldsymbol\delta = 0\) (row \(i\) of Fact 3 set to zero): straight lines that touch the curved ones near \(\mathbf x_k\). Where they cross is the solution of \(J\boldsymbol\delta = -\mathbf F\), the next iterate (yellow dot). The readout gives \(\mathbf F\), \(J\), \(\det J\) and \(\boldsymbol\delta\) at \(\mathbf x_k\), where the run ends, and the error \(\|\mathbf x_k - \mathbf x^*\|\) of every iterate. The run stops when \(\|\mathbf F\| < 10^{-12}\) or after 50 steps.
basins colours every start by the steady state Newton reaches from it (black: no convergence), computed on a grid, and gives the shares for starts in \([0, 4]^2\), as in the lecture’s basin figure. det J = 0 draws the dotted curve where the Jacobian is singular. The sliders change \(\alpha\) and \(n\).
E1. (linearise, solve, repeat) Click the start (3, 0.5) and + 1 once. Read \(\mathbf F\), \(J\), \(\det J\), \(\boldsymbol\delta\) and \(\mathbf x_1\) and compare with the lecture’s step by hand. Where do the two dashed lines cross? Keep clicking + 1 until the run stops. How many steps does it take, and how do the errors per step show quadratic convergence?
\(\mathbf F(\mathbf x_0) = (-0.6, -0.2)\), \(J = \begin{pmatrix}-1 & -1.92\\ -0.18 & -1\end{pmatrix}\), \(\det J = 0.654\), \(\boldsymbol\delta = (-0.330073, -0.140587)\), \(\mathbf x_1 = (2.669927, 0.359413)\): the same as by hand. The dashed lines cross exactly at \(\mathbf x_1\): each dashed line is where one component of the linear approximation is zero, so their crossing is where both are, the solution of \(J\boldsymbol\delta = -\mathbf F\). Near the “U high” state the dashed lines lie almost on top of the curves, so their crossing is almost the root. The run ends at \((2.618034, 0.381966)\) after 5 steps, with errors \(0.400\), \(0.0566\), \(2.1\times10^{-3}\), \(2.9\times10^{-6}\), \(5.9\times10^{-12}\), \(\approx 0\): the exponent roughly doubles each step.
E2. (which root?) Click the starts (1, 0.2) and (1, 1) and step through each. Where does each run end, and why? Then tick basins. What shares do you read for starts in \([0, 4]^2\)? Drag the start slowly from \((1, 0.2)\) to the right along \(v = 0.2\): where does the answer switch to “U high”?
From \((1, 0.2)\) the first step jumps to \((0.334, 2.499)\) and the run ends in V high \((0.381966, 2.618034)\) after 5 steps, although \(u > v\) at the start: the crossing of the linearised nullclines happens to lie up on the left. From \((1, 1)\) every iterate stays on the diagonal (\((1.2, 1.2)\) after one step, B8) and the run ends in the middle state \((1.213412, 1.213412)\) after 4 steps. The basin shares are U high 21 %, middle 57 %, V high 21 %, no convergence 0 %, as in the lecture: the unstable middle state is Newton’s most common answer. Along \(v = 0.2\) the start stays in the purple (V high) region up to \(u \approx 1.4\); between about \(1.45\) and \(1.55\) the answer flips between middle, U high and V high in a thin band, and from \(u \approx 1.6\) on the run ends in U high. The boundaries are curved and have nothing to do with the diagonal \(u = v\) that separates the cell’s two fates.
E3. (a nearly singular Jacobian) Click (1.9, 0.5) and + 1. Read \(\det J\) and \(\mathbf x_1\), then follow the run to the end. Do the same for (2, 0.55). Now tick det J = 0. Where do the two starts lie relative to the dotted curve, and what does the basin picture look like near it?
At \((1.9, 0.5)\): \(\det J = -0.0299\) (“nearly singular”); the dashed lines are almost parallel, so they cross far away: \(\mathbf x_1 = (-5.14, 4.43)\), off the plot, with a negative concentration. From there the run comes back and ends in the middle state after 7 steps. At \((2, 0.55)\): \(\det J = 0.0663\), \(\mathbf x_1 = (5.106, -0.891)\), also a huge step, but it ends in U high after 7 steps. Both starts lie just on either side of the dotted curve \(\det J = 0\). Along that curve the basins break into thin interleaved bands of all three colours: a tiny change of the start sends the first step to a very different place.
E4. (bistability needs \(\alpha > 2\)) Keep basins on, start at (3, 0.5), and lower \(\alpha\): \(2.5\), \(2.2\), \(2.05\), \(2\), \(1.5\). For each, count the steady states and read the shares. Compare the “U high” state with \(u = (\alpha + \sqrt{\alpha^2 - 4})/2\) from B5. What is special about \(\alpha = 2\): the number of steps, the errors per step, and the black area?
| \(\alpha\) | steady states | U high | shares (U high / middle / V high / none) |
|---|---|---|---|
| 2.5 | 3 | \((2.000000, 0.500000)\) | 24 / 53 / 24 / 0 % |
| 2.2 | 3 | \((1.558258, 0.641742)\) | 27 / 47 / 27 / 0 % |
| 2.05 | 3 | \((1.250000, 0.800000)\) | 36 / 29 / 36 / 0 % |
| 2 | 1, at \((1, 1)\) | — | 93 % reach it, 7 % no convergence |
| 1.5 | 1, at \((0.861224, 0.861224)\) | — | 100 % |
The U-high states agree with \((\alpha + \sqrt{\alpha^2-4})/2\): \(2\), \(1.5583\), \(1.25\). As \(\alpha \to 2\) the three states move together and at \(\alpha = 2\) they merge at \((1, 1)\), where \(\det J = 0\): the Jacobian is singular at the root. From \((3, 0.5)\) the run then needs 39 steps instead of 5–8, and the errors per step shrink only by a factor of about \(2/3\) (\(0.67\), \(0.44\), \(0.28\), …): linear, not quadratic, convergence, like Newton at a multiple root in one variable. The 7 % black starts are runs that are still crawling after 50 steps. Below \(\alpha = 2\) there is one state, the circuit is no switch, and every start finds it.
E5. (the Hill coefficient) Reset, then set \(n = 2.5\) (with \(\alpha = 3\)) and click (2, 0.5). What happens after one step, and why? Tick basins: how large is the black area now? Finally set \(n = 1\) and try \(\alpha\) between 1 and 5. Is the switch ever bistable?
With \(n = 2.5\) the first step from \((2, 0.5)\) goes to \((9.72, -3.25)\); then \(v^{2.5}\) of a negative number is NaN, and the run ends with NaN after 1 step (the lecture’s Failure 1). The steady states still exist (“U high” at \((2.955096, 0.187363)\)), but the shares are U high 16 %, middle 33 %, V high 16 %, no convergence 34 %: every start whose path visits negative concentrations fails. With \(n = 1\) there is a single steady state for every \(\alpha\) (at \(\alpha = 3\): \(u = v = 1.302776\)): without cooperativity no bistability. The black regions there are runs that wander around the poles at \(u = -1\) or \(v = -1\), where \(1 + u^n = 0\).
Hints
Pretend the other variable is a number like 7. For \(\alpha(1 + v^n)^{-1}\): the derivative of \((\cdot)^{-1}\) is \(-(\cdot)^{-2}\), times the derivative of the inside, \(n v^{n-1}\). For \(r(S, E)\) in \(S\), use the quotient rule: \(\dfrac{d}{dS}\dfrac{S}{K+S} = \dfrac{K}{(K+S)^2}\).
Write the two equations out. Use one equation to express one unknown in terms of the other, and substitute. For \(\begin{pmatrix} a & b\\ c & d\end{pmatrix}\boldsymbol\delta = \mathbf r\) the closed form is \(\delta_1 = (d r_1 - b r_2)/\det\), \(\delta_2 = (a r_2 - c r_1)/\det\) with \(\det = ad - bc\). Remember the right-hand side is \(-\mathbf F\).
\(u(1 + v^2) - v(1 + u^2) = (u - v) + uv(v - u)\). Factor out \((u - v)\). With \(uv = 1\), \(u(1 + v^2) = u + v\,(uv) = u + v\). Two numbers with sum \(\alpha\) and product 1 are the roots of \(t^2 - \alpha t + 1 = 0\).
R: solve(A, b) solves \(A\mathbf x = \mathbf b\); collect the iterates with rbind. Python: np.linalg.solve, collect them in a list and convert with np.array. Rust: jac(&x).lu().solve(&(-f(&x))) returns None if the matrix is singular. For the grid of starts: R expand.grid and apply; distinct rows with unique after round. Python: np.unique(..., axis=0, return_counts=True).
Copy x, add \(h_j\) to entry \(j\) only, and fill column \(j\) with the difference of the two \(\mathbf F\) vectors divided by \(h_j\). In R, .Machine$double.eps; in Python, np.finfo(float).eps; in Rust, f64::EPSILON. For C4, pass a small function function(x) fd_jacobian(F, x, h) (Python: lambda x: fd_jacobian(F, x, h)) as the Jacobian.
multiroot(f, start, jacfunc = NULL, rtol, atol, ctol) returns a list with root, f.root (the residual), iter and estim.precis. scipy.optimize.root(fun, x0, jac=None, tol=None) returns an object with .x, .fun, .nfev and .success. Always look at the residual, not just at success.
A negative number raised to a non-integer power is NaN in R and numpy (and in Rust’s powf). For the damped step, a while loop that halves t; stop with an error if t becomes tiny. In C7, wrap the Newton call in tryCatch (Python: try/except np.linalg.LinAlgError) because the Jacobian can be exactly singular. At \(\alpha = 2\), compute \(\det J\) at the root \(u = v = 1\).
Solutions
B1. (a) \(\partial g/\partial u = 2uv\) (treat \(v\) as a constant), \(\partial g/\partial v = u^2 + 3\) (treat \(u\) as a constant). At \((1, 2)\): \(\partial g/\partial u = 4\), \(\partial g/\partial v = 4\). (b) \(\partial r/\partial E = \dfrac{kS}{K + S} = \dfrac{2\cdot1}{2} = 1\): one more unit of enzyme raises the rate by 1 unit (the rate is proportional to \(E\)). \(\partial r/\partial S = kE\,\dfrac{K}{(K+S)^2} = 2\cdot0.5\cdot\dfrac{1}{4} = 0.25\): at \(S = K\) the enzyme is half saturated, and one more unit of substrate raises the rate by only 0.25. (c) \(r(1.01, 0.5) = 2\cdot0.5\cdot1.01/2.01 = 0.502488\), \(r(1, 0.5) = 0.5\), so the quotient is \(0.002488/0.01 = 0.2488\), close to \(0.25\) (the forward difference has an error of order \(h\)).
B2. (a) \(\partial F_1/\partial u = -1\), \(\partial F_1/\partial v = \alpha\cdot\big(-(1+v^n)^{-2}\big)\cdot n v^{n-1} = -\dfrac{\alpha n v^{n-1}}{(1+v^n)^2}\); by symmetry \(\partial F_2/\partial u = -\dfrac{\alpha n u^{n-1}}{(1+u^n)^2}\) and \(\partial F_2/\partial v = -1\). (b) At \((1, 2)\): \(\partial F_1/\partial v = -\dfrac{6\cdot2}{5^2} = -0.48\), \(\partial F_2/\partial u = -\dfrac{6\cdot1}{2^2} = -1.5\). So \(J = \begin{pmatrix} -1 & -0.48\\ -1.5 & -1\end{pmatrix}\). (c) The diagonal \(-1\) is degradation/dilution: each protein lowers its own rate of change. The off-diagonal entries are repression. At \((1, 2)\), \(u = 1\) sits exactly at the repression threshold, the steepest part of the Hill curve, so a change in U has a strong effect on V’s production (\(-1.5\)). \(v = 2\) is above threshold, where the Hill curve flattens, so V’s effect on U is weaker (\(-0.48\)). (d) At \(u = v = 1.2134\): off-diagonals \(-\dfrac{6\cdot1.2134}{(1 + 1.4724)^2} = -\dfrac{7.2805}{6.1128} = -1.1911\), so \(J = \begin{pmatrix} -1 & -1.1911\\ -1.1911 & -1\end{pmatrix}\) and \(\det J = 1 - 1.1911^2 = -0.4186\). Not singular, so Newton converges quadratically there too.
B3. \(\mathbf F(1, 2) = (3/5 - 1,\; 3/2 - 2) = (-0.4, -0.5)\). With \(\boldsymbol\delta = (0.1, -0.1)\): \(J\boldsymbol\delta = (-0.1 + 0.048,\; -0.15 + 0.1) = (-0.052, -0.05)\), so the prediction is \((-0.452, -0.550)\). True: \(\mathbf F(1.1, 1.9) = (3/4.61 - 1.1,\; 3/2.21 - 1.9) = (-0.4492, -0.5425)\). The prediction is off by about \(0.003\) and \(0.007\), of the order of \(\|\boldsymbol\delta\|^2 = 0.02\), as Fact 3 says.
B4. (a) \(\mathbf F(3, 0) = (3/1 - 3,\; 3/10 - 0) = (0, 0.3)\). \(J(3, 0) = \begin{pmatrix} -1 & 0\\ -0.18 & -1\end{pmatrix}\): at \(v = 0\) the Hill curve is flat (\(\partial F_1/\partial v = 0\)), so \(J\) is triangular. (b) Row 1: \(-\delta_u = 0\), so \(\delta_u = 0\). Row 2: \(-0.18\cdot0 - \delta_v = -0.3\), so \(\delta_v = 0.3\). \(\mathbf x_1 = (3, 0.3)\). (c) \(\mathbf F(3, 0.3) = (3/1.09 - 3,\; 0.3 - 0.3) = (-0.24771, 0)\). \(\partial F_1/\partial v = -6\cdot0.3/1.09^2 = -1.51502\), \(\partial F_2/\partial u = -0.18\). Solve \(\begin{pmatrix} -1 & -1.51502\\ -0.18 & -1\end{pmatrix}\boldsymbol\delta = \begin{pmatrix} 0.24771\\ 0\end{pmatrix}\). Row 2 gives \(\delta_v = -0.18\,\delta_u\); row 1 then gives \((-1 + 0.27270)\,\delta_u = 0.24771\), so \(\delta_u = -0.34058\), \(\delta_v = 0.06131\). \(\mathbf x_2 = (2.6594, 0.3613)\), error about \(0.046\) (C2 confirms these digits).
B5. (a) \(u + uv^2 - v - vu^2 = (u - v) - uv(u - v) = (u - v)(1 - uv) = 0\). (b) \(u = v\) in \(u(1 + u^2) = \alpha\) gives \(u^3 + u - \alpha = 0\). Newton with \(f(u) = u^3 + u - 3\), \(f'(u) = 3u^2 + 1\): \(u_1 = 1 - (-1)/4 = 1.25\); \(u_2 = 1.25 - 0.203125/5.6875 = 1.21429\). (The root is \(1.213412\).) (c) With \(uv = 1\): \(u(1 + v^2) = u + v(uv) = u + v = \alpha\). So \(u, v\) are the roots of \(t^2 - 3t + 1 = 0\): \(t = (3 \pm \sqrt5)/2\), i.e. \((u, v) = (2.618034, 0.381966)\) or \((0.381966, 2.618034)\). (These are \(\varphi^2\) and \(1/\varphi^2\), with \(\varphi\) the golden ratio.) (d) \(t^2 - \alpha t + 1 = 0\) has real roots when \(\alpha^2 - 4 \ge 0\), i.e. \(\alpha \ge 2\) (both positive, since their product is 1 and their sum \(\alpha > 0\)). For \(\alpha < 2\) only the symmetric state exists: the circuit is not a switch. For \(\alpha > 2\) there are three steady states: bistable. At \(\alpha = 2\) all three merge at \(u = v = 1\).
B6. \(J = A\), constant. From any \(\mathbf x_0\): \(A\boldsymbol\delta = -(A\mathbf x_0 - \mathbf b)\), so \(\mathbf x_1 = \mathbf x_0 + \boldsymbol\delta = \mathbf x_0 - \mathbf x_0 + A^{-1}\mathbf b = A^{-1}\mathbf b\), the exact root. The linear approximation is exact for a linear function, so one step suffices. (Newton is “solve the linear problem, repeat”; for a linear problem there is nothing to repeat.)
B7. (a) \(\mathbf F(3, 0.51) = (3/1.2601 - 3,\; 0.3 - 0.51) = (-0.619237, -0.21)\), \(\mathbf F(3, 0.5) = (-0.6, -0.2)\). Column 2 \(= (-0.019237, -0.01)/0.01 = (-1.9237, -1)\). Exact: \((-1.92, -1)\). The error \(0.0037\) is about \(h\,|\partial^2 F_1/\partial v^2|/2\), as for any forward difference. (b) \(\mathbf F(3.01, 0.5) = (2.4 - 3.01,\; 3/10.0601 - 0.5) = (-0.61, -0.201792)\). Column 1 \(= (-0.01, -0.001792)/0.01 = (-1, -0.1792)\). Exact: \((-1, -0.18)\). (c) 3 evaluations: \(\mathbf F(\mathbf x)\) once, plus one per column. For 100 genes: 101 evaluations.
B8. (a) With \(u = v\): \(F_1 = \alpha/(1 + u^n) - u = F_2\). The off-diagonal entries are the same function evaluated at \(v\) and at \(u\), so they are equal (\(= b\), say), and both diagonal entries are \(-1\). The system \(\begin{pmatrix} -1 & b\\ b & -1\end{pmatrix}\boldsymbol\delta = -\begin{pmatrix} F_1\\ F_1\end{pmatrix}\) is unchanged when we swap \(\delta_u\) and \(\delta_v\), so its unique solution has \(\delta_u = \delta_v\). Every iterate stays on the diagonal, so Newton can only find the middle state \((1.2134, 1.2134)\). (b) \(n = 2\): about 5 operations, nanoseconds. \(n = 1000\): \(6.7\times10^8\) operations, 0.67 s. \(n = 20\,000\): \(5.3\times10^{12}\), about 1.5 hours per step. Building the Jacobian costs \((n + 1)\cdot10n \approx 10n^2\) operations: \(10^7\) for \(n = 1000\) and \(4\times10^9\) for \(n = 20\,000\), small compared with the solve. For large dense problems the linear solve dominates; for cheap \(\mathbf F\) and sparse \(J\) the balance changes (Part 3).
C1.
# uses F(), J() from the Background
fd_jacobian <- function(F, x, h = sqrt(.Machine$double.eps)) {
Fx <- F(x)
Jm <- matrix(0, length(Fx), length(x))
for (j in seq_along(x)) {
hj <- h * max(abs(x[j]), 1) # step relative to the size of x[j]
xh <- x; xh[j] <- x[j] + hj # nudge only x[j]
Jm[, j] <- (F(xh) - Fx) / hj # column j
}
Jm
}
J(c(1, 2)) # B2
# [,1] [,2]
# [1,] -1.0 -0.48
# [2,] -1.5 -1.00
for (x in list(c(3, 0.5), c(1, 2), c(1.2, 1.2), c(0.1, 4))) {
cat(x, ":", max(abs(fd_jacobian(F, x) - J(x))), "\n")
}
# 3 0.5 : 1.311302e-08
# 1 2 : 1.490116e-08
# 1.2 1.2 : 1.017171e-08
# 0.1 4 : 5.132509e-08
library(numDeriv)
max(abs(jacobian(F, c(1, 2)) - J(c(1, 2)))) # Richardson extrapolation: more digits
# [1] 6.565803e-12# uses F(), J() from the Background
from scipy.optimize import approx_fprime
def fd_jacobian(F, x, h=np.sqrt(np.finfo(float).eps)):
Fx = F(x)
Jm = np.zeros((len(Fx), len(x)))
for j in range(len(x)):
hj = h * max(abs(x[j]), 1) # step relative to the size of x[j]
xh = x.copy(); xh[j] += hj # nudge only x[j]
Jm[:, j] = (F(xh) - Fx) / hj # column j
return Jm
print(J(np.array([1.0, 2.0]))) # B2
# [[-1. -0.48]
# [-1.5 -1. ]]
for x in [[3, 0.5], [1, 2], [1.2, 1.2], [0.1, 4]]:
x = np.array(x, dtype=float)
print(x, ":", np.max(np.abs(fd_jacobian(F, x) - J(x))))
# [3. 0.5] : 1.3113021779531664e-08
# [1. 2.] : 1.4901161193847656e-08
# [1.2 1.2] : 1.017171435968578e-08
# [0.1 4. ] : 5.1325085625997247e-08
x = np.array([1.0, 2.0])
print(np.max(np.abs(approx_fprime(x, F) - J(x)))) # scipy's forward difference
# 1.4901161193847656e-08// rust/examples/newton_systems_c1.rs — cargo run --example newton_systems_c1
// C1: check the hand-derived Jacobian against a finite-difference Jacobian.
use nalgebra::{DMatrix, DVector};
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
fn f(x: &DVector<f64>) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v])
}
fn jac(x: &DVector<f64>) -> DMatrix<f64> {
let (u, v) = (x[0], x[1]);
DMatrix::from_row_slice(2, 2, &[
-1.0, -ALPHA * N * v.powf(N - 1.0) / (1.0 + v.powf(N)).powi(2),
-ALPHA * N * u.powf(N - 1.0) / (1.0 + u.powf(N)).powi(2), -1.0])
}
// works for any F: R^n -> R^m (here passed as a function)
fn fd_jacobian(f: impl Fn(&DVector<f64>) -> DVector<f64>, x: &DVector<f64>, h: f64) -> DMatrix<f64> {
let fx = f(x);
let mut jm = DMatrix::zeros(fx.len(), x.len());
for j in 0..x.len() {
let hj = h * x[j].abs().max(1.0); // step relative to the size of x[j]
let mut xh = x.clone();
xh[j] += hj; // nudge only x[j]
jm.set_column(j, &((f(&xh) - &fx) / hj)); // column j
}
jm
}
fn main() {
let h = f64::EPSILON.sqrt();
println!("{}", jac(&DVector::from_vec(vec![1.0, 2.0]))); // B2
for p in [[3.0, 0.5], [1.0, 2.0], [1.2, 1.2], [0.1, 4.0]] {
let x = DVector::from_vec(p.to_vec());
let diff = (fd_jacobian(f, &x, h) - jac(&x)).abs().max();
println!("{:?} : {:e}", p, diff);
}
}
// Output:
//
// ┌ ┐
// │ -1 -0.48 │
// │ -1.5 -1 │
// └ ┘
//
//
// [3.0, 0.5] : 1.3113021779531664e-8
// [1.0, 2.0] : 1.4901161193847656e-8
// [1.2, 1.2] : 1.017171435968578e-8
// [0.1, 4.0] : 5.1325085625997247e-8The hand-derived and finite-difference Jacobians agree to about \(10^{-8}\) everywhere, as expected for \(h = \sqrt\varepsilon\). A wrong entry (a sign, a missing factor \(n\)) would show up as a difference of order 1. numDeriv::jacobian uses Richardson extrapolation and gets \(7\times10^{-12}\); approx_fprime is a plain forward difference like ours.
C2.
# uses F(), J() from the Background
newton_sys <- function(F, J, x, tol = 1e-12, maxit = 50) {
path <- matrix(x, nrow = 1) # row k+1 = x_k
for (k in 1:maxit) {
delta <- solve(J(x), -F(x)) # one linear solve per step
x <- x + delta
path <- rbind(path, x, deparse.level = 0)
if (sqrt(sum(delta^2)) < tol) return(path)
}
warning("no convergence")
path
}
xstar <- c((3 + sqrt(5)) / 2, (3 - sqrt(5)) / 2) # exact, from B5
P <- newton_sys(F, J, c(3, 0))
print(P[1:3, ], digits = 6) # compare with B4
# [,1] [,2]
# [1,] 3.00000 0.000000
# [2,] 3.00000 0.300000
# [3,] 2.65941 0.361305
P <- newton_sys(F, J, c(3, 0.5))
err <- sqrt(rowSums((P - matrix(xstar, nrow(P), 2, byrow = TRUE))^2))
res <- apply(P, 1, function(x) sqrt(sum(F(x)^2)))
print(cbind(k = 0:(nrow(P) - 1), err, res), digits = 3)
# k err res
# [1,] 0 4.00e-01 6.32e-01
# [2,] 1 5.66e-02 1.63e-02
# [3,] 2 2.11e-03 6.49e-04
# [4,] 3 2.93e-06 8.32e-07
# [5,] 4 5.86e-12 1.72e-12
# [6,] 5 5.55e-17 0.00e+00
# [7,] 6 5.55e-17 0.00e+00
err[2:5] / err[1:4]^2 # quadratic: roughly constant
# [1] 0.3540110 0.6576423 0.6604449 0.6842132# uses F(), J() from the Background
import warnings
def newton_sys(F, J, x, tol=1e-12, maxit=50):
path = [x] # path[k] = x_k
for k in range(maxit):
delta = np.linalg.solve(J(x), -F(x)) # one linear solve per step
x = x + delta
path.append(x)
if np.sqrt(np.sum(delta**2)) < tol:
return np.array(path)
warnings.warn("no convergence")
return np.array(path)
xstar = np.array([(3 + np.sqrt(5)) / 2, (3 - np.sqrt(5)) / 2]) # exact, from B5
P = newton_sys(F, J, np.array([3.0, 0.0]))
print(P[:3]) # compare with B4
# [[3. 0. ]
# [3. 0.3 ]
# [2.65941442 0.3613054 ]]
P = newton_sys(F, J, np.array([3.0, 0.5]))
err = np.sqrt(np.sum((P - xstar)**2, axis=1))
res = np.array([np.sqrt(np.sum(F(x)**2)) for x in P])
for k in range(len(P)):
print(f"{k} {err[k]:.3g} {res[k]:.3g}")
# 0 0.4 0.632
# 1 0.0566 0.0163
# 2 0.00211 0.000649
# 3 2.93e-06 8.32e-07
# 4 5.86e-12 1.72e-12
# 5 5.55e-17 0
# 6 5.55e-17 0
print(err[1:5] / err[0:4]**2) # quadratic: roughly constant
# [0.35401101 0.65764228 0.66044492 0.68421325]// rust/examples/newton_systems_c2.rs — cargo run --example newton_systems_c2
// C2: Newton for the toggle switch; quadratic convergence.
use nalgebra::{DMatrix, DVector};
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
fn f(x: &DVector<f64>) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v])
}
fn jac(x: &DVector<f64>) -> DMatrix<f64> {
let (u, v) = (x[0], x[1]);
DMatrix::from_row_slice(2, 2, &[
-1.0, -ALPHA * N * v.powf(N - 1.0) / (1.0 + v.powf(N)).powi(2),
-ALPHA * N * u.powf(N - 1.0) / (1.0 + u.powf(N)).powi(2), -1.0])
}
// returns the path x_0, x_1, ...; None if J is exactly singular at some step
fn newton_sys(f: impl Fn(&DVector<f64>) -> DVector<f64>,
jac: impl Fn(&DVector<f64>) -> DMatrix<f64>,
x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<Vec<DVector<f64>>> {
let mut x = x0.clone();
let mut path = vec![x.clone()];
for _ in 0..maxit {
let delta = jac(&x).lu().solve(&(-f(&x)))?; // one linear solve per step
x += δ
path.push(x.clone());
if delta.norm() < tol { // norm() = sqrt(sum of squares)
return Some(path);
}
}
eprintln!("warning: no convergence");
Some(path)
}
fn v2(a: f64, b: f64) -> DVector<f64> { DVector::from_vec(vec![a, b]) }
fn main() {
let xstar = v2((3.0 + 5f64.sqrt()) / 2.0, (3.0 - 5f64.sqrt()) / 2.0); // exact, from B5
let p = newton_sys(f, jac, &v2(3.0, 0.0), 1e-12, 50).unwrap();
for x in &p[0..3] {
println!("{:.6} {:.6}", x[0], x[1]); // compare with B4
}
let p = newton_sys(f, jac, &v2(3.0, 0.5), 1e-12, 50).unwrap();
let err: Vec<f64> = p.iter().map(|x| (x - &xstar).norm()).collect();
for (k, x) in p.iter().enumerate() {
println!("{} {:.2e} {:.2e}", k, err[k], f(x).norm());
}
let ratio: Vec<f64> = (0..4).map(|k| err[k + 1] / err[k].powi(2)).collect();
println!("{:?}", ratio); // quadratic: roughly constant
}
// Output:
// 3.000000 0.000000
// 3.000000 0.300000
// 2.659414 0.361305
// 0 4.00e-1 6.32e-1
// 1 5.66e-2 1.63e-2
// 2 2.11e-3 6.49e-4
// 3 2.93e-6 8.32e-7
// 4 5.86e-12 1.72e-12
// 5 5.55e-17 0.00e0
// 6 5.55e-17 0.00e0
// [0.35401101412575076, 0.6576422802285518, 0.6604449241015179, 0.6842132498408281]The first steps from \((3, 0)\) match B4. From \((3, 0.5)\) the error goes \(0.4 \to 0.057 \to 0.0021 \to 2.9\times10^{-6} \to 5.9\times10^{-12} \to 10^{-16}\): the exponent roughly doubles each step, and \(e_{k+1}/e_k^2\) settles near \(0.66\). That is quadratic convergence. After step 5 the error is at the rounding level and cannot shrink further.
C3.
# uses F() from the Background; newton_sys() from the solution of C2
g <- seq(0.2, 3.8, by = 0.4) # 10 values
starts <- as.matrix(expand.grid(u = g, v = g)) # 100 starts
roots <- t(apply(starts, 1, function(s) {
P <- newton_sys(F, J, s)
P[nrow(P), ] # last iterate
}))
key <- round(roots, 6) # equal to 6 decimals = same root
distinct <- unique(key)
distinct
# u v
# [1,] 1.213412 1.213412
# [2,] 0.381966 2.618034
# [3,] 2.618034 0.381966
table(apply(key, 1, paste, collapse = " ")) / nrow(key)
#
# 0.381966 2.618034 1.213412 1.213412 2.618034 0.381966
# 0.23 0.54 0.23
max(apply(roots, 1, function(x) sqrt(sum(F(x)^2)))) # worst residual of all 100 runs
# [1] 4.577567e-16# uses F() from the Background; newton_sys() from the solution of C2
g = np.arange(0.2, 3.81, 0.4) # 10 values
starts = [np.array([u, v]) for v in g for u in g] # 100 starts
roots = np.array([newton_sys(F, J, s)[-1] for s in starts]) # last iterates
key = np.round(roots, 6) # equal to 6 decimals = same root
distinct, counts = np.unique(key, axis=0, return_counts=True)
print(distinct)
# [[0.381966 2.618034]
# [1.213412 1.213412]
# [2.618034 0.381966]]
print(counts / len(key))
# [0.23 0.54 0.23]
print(max(np.sqrt(np.sum(F(x)**2)) for x in roots)) # worst residual of all 100 runs
# 4.577566798522237e-16// rust/examples/newton_systems_c3.rs — cargo run --example newton_systems_c3
// C3: Newton from 100 starts; collect the distinct steady states.
use nalgebra::{DMatrix, DVector};
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
fn f(x: &DVector<f64>) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v])
}
fn jac(x: &DVector<f64>) -> DMatrix<f64> {
let (u, v) = (x[0], x[1]);
DMatrix::from_row_slice(2, 2, &[
-1.0, -ALPHA * N * v.powf(N - 1.0) / (1.0 + v.powf(N)).powi(2),
-ALPHA * N * u.powf(N - 1.0) / (1.0 + u.powf(N)).powi(2), -1.0])
}
// returns the path x_0, x_1, ...; None if J is exactly singular at some step
fn newton_sys(f: impl Fn(&DVector<f64>) -> DVector<f64>,
jac: impl Fn(&DVector<f64>) -> DMatrix<f64>,
x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<Vec<DVector<f64>>> {
let mut x = x0.clone();
let mut path = vec![x.clone()];
for _ in 0..maxit {
let delta = jac(&x).lu().solve(&(-f(&x)))?; // one linear solve per step
x += δ
path.push(x.clone());
if delta.norm() < tol { // norm() = sqrt(sum of squares)
return Some(path);
}
}
eprintln!("warning: no convergence");
Some(path)
}
fn v2(a: f64, b: f64) -> DVector<f64> { DVector::from_vec(vec![a, b]) }
fn main() {
let g: Vec<f64> = (0..10).map(|i| 0.2 + 0.4 * i as f64).collect(); // 10 values
let mut roots: Vec<DVector<f64>> = Vec::new();
for &v in &g {
for &u in &g {
let p = newton_sys(f, jac, &v2(u, v), 1e-12, 50).unwrap();
roots.push(p.last().unwrap().clone()); // last iterate
}
}
// equal to 6 decimals = same root; count how often each one is found
let mut distinct: Vec<([f64; 2], usize)> = Vec::new();
for r in &roots {
let key = [(r[0] * 1e6).round() / 1e6, (r[1] * 1e6).round() / 1e6];
match distinct.iter_mut().find(|(k, _)| *k == key) {
Some((_, c)) => *c += 1,
None => distinct.push((key, 1)),
}
}
for (k, c) in &distinct {
println!("{:?} {:.2}", k, *c as f64 / roots.len() as f64);
}
let worst = roots.iter().map(|x| f(x).norm()).fold(0.0, f64::max);
println!("{:e}", worst); // worst residual of all 100 runs
}
// Output:
// [1.213412, 1.213412] 0.54
// [0.381966, 2.618034] 0.23
// [2.618034, 0.381966] 0.23
// 4.577566798522237e-16All 100 runs converge (worst residual \(5\times10^{-16}\)), to only three distinct roots: 23 % to “U on”, 23 % to “V on” and 54 % to the unstable middle state, close to the 57 % in the lecture’s basin picture (a finer grid on a slightly different square). Newton has no preference for stable states.
C4.
# uses fd_jacobian() from the solution of C1; newton_sys() from the solution of C2
for (h in c(sqrt(.Machine$double.eps), 1e-4, 1e-2, 0.3)) {
Jfd <- function(x) fd_jacobian(F, x, h)
P <- newton_sys(F, Jfd, c(3, 0.5))
err <- sqrt(rowSums((P - matrix(xstar, nrow(P), 2, byrow = TRUE))^2))
cat(sprintf("h = %.1e: %d steps; errors %s\n", h, nrow(P) - 1,
paste(sprintf("%.0e", err[2:6]), collapse = " ")))
}
# h = 1.5e-08: 6 steps; errors 6e-02 2e-03 3e-06 6e-12 1e-16
# h = 1.0e-04: 6 steps; errors 6e-02 2e-03 3e-06 1e-10 2e-14
# h = 1.0e-02: 8 steps; errors 6e-02 2e-03 1e-05 1e-07 1e-09
# h = 3.0e-01: 15 steps; errors 1e-01 1e-02 6e-04 2e-04 3e-05# uses fd_jacobian() from the solution of C1; newton_sys() from the solution of C2
for h in [np.sqrt(np.finfo(float).eps), 1e-4, 1e-2, 0.3]:
Jfd = lambda x: fd_jacobian(F, x, h)
P = newton_sys(F, Jfd, np.array([3.0, 0.5]))
err = np.sqrt(np.sum((P - xstar)**2, axis=1))
print(f"h = {h:.1e}: {len(P) - 1} steps; errors",
" ".join(f"{e:.0e}" for e in err[1:6]))
# h = 1.5e-08: 6 steps; errors 6e-02 2e-03 3e-06 6e-12 1e-16
# h = 1.0e-04: 6 steps; errors 6e-02 2e-03 3e-06 1e-10 2e-14
# h = 1.0e-02: 8 steps; errors 6e-02 2e-03 1e-05 1e-07 1e-09
# h = 3.0e-01: 15 steps; errors 1e-01 1e-02 6e-04 2e-04 3e-05// rust/examples/newton_systems_c4.rs — cargo run --example newton_systems_c4
// C4: Newton with a finite-difference Jacobian, for several step sizes h.
use nalgebra::{DMatrix, DVector};
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
fn f(x: &DVector<f64>) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v])
}
// returns the path x_0, x_1, ...; None if J is exactly singular at some step
fn newton_sys(f: impl Fn(&DVector<f64>) -> DVector<f64>,
jac: impl Fn(&DVector<f64>) -> DMatrix<f64>,
x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<Vec<DVector<f64>>> {
let mut x = x0.clone();
let mut path = vec![x.clone()];
for _ in 0..maxit {
let delta = jac(&x).lu().solve(&(-f(&x)))?; // one linear solve per step
x += δ
path.push(x.clone());
if delta.norm() < tol { // norm() = sqrt(sum of squares)
return Some(path);
}
}
eprintln!("warning: no convergence");
Some(path)
}
fn v2(a: f64, b: f64) -> DVector<f64> { DVector::from_vec(vec![a, b]) }
fn fd_jacobian(f: impl Fn(&DVector<f64>) -> DVector<f64>, x: &DVector<f64>, h: f64) -> DMatrix<f64> {
let fx = f(x);
let mut jm = DMatrix::zeros(fx.len(), x.len());
for j in 0..x.len() {
let hj = h * x[j].abs().max(1.0);
let mut xh = x.clone();
xh[j] += hj;
jm.set_column(j, &((f(&xh) - &fx) / hj));
}
jm
}
fn main() {
let xstar = v2((3.0 + 5f64.sqrt()) / 2.0, (3.0 - 5f64.sqrt()) / 2.0);
for h in [f64::EPSILON.sqrt(), 1e-4, 1e-2, 0.3] {
let jfd = |x: &DVector<f64>| fd_jacobian(f, x, h);
let p = newton_sys(f, jfd, &v2(3.0, 0.5), 1e-12, 50).unwrap();
let errs: Vec<String> = p[1..6].iter()
.map(|x| format!("{:.0e}", (x - &xstar).norm())).collect();
println!("h = {:.1e}: {} steps; errors {}", h, p.len() - 1, errs.join(" "));
}
}
// Output:
// h = 1.5e-8: 6 steps; errors 6e-2 2e-3 3e-6 6e-12 1e-16
// h = 1.0e-4: 6 steps; errors 6e-2 2e-3 3e-6 1e-10 2e-14
// h = 1.0e-2: 8 steps; errors 6e-2 2e-3 1e-5 1e-7 1e-9
// h = 3.0e-1: 15 steps; errors 1e-1 1e-2 6e-4 2e-4 3e-5With \(h = \sqrt\varepsilon\) the run is indistinguishable from the exact Jacobian. With \(h = 10^{-4}\) the Jacobian has about 4 correct digits and the last steps gain fewer digits. With \(h = 10^{-2}\) and \(0.3\) the convergence becomes linear (a roughly constant factor per step) and needs more steps. An approximate Jacobian still converges to the right root, because the root is defined by \(\mathbf F = \mathbf 0\), not by \(J\); only the speed suffers. This is why quasi-Newton methods, which reuse an approximate Jacobian, work (Part 10).
C5.
library(rootSolve)
sol <- multiroot(f = F, start = c(3, 0.5)) # finite-difference Jacobian
print(sol$root, digits = 15); sol$f.root; sol$iter
# [1] 2.61803398875534 0.38196601124783
# [1] -1.471712e-12 8.891221e-13
# [1] 5
sol$root - xstar
# [1] 5.442313e-12 -2.274902e-12
sol <- multiroot(f = F, start = c(3, 0.5), jacfunc = J, atol = 1e-14, rtol = 1e-14)
print(sol$root, digits = 15); sol$f.root; sol$iter
# [1] 2.618033988749895 0.381966011250105
# [1] 0.000000e+00 -5.551115e-17
# [1] 6
sol$root - xstar
# [1] 0.000000e+00 1.110223e-16
for (s in list(c(0.5, 3), c(1, 1), c(1, 0.2))) print(multiroot(F, s)$root)
# [1] 0.381966 2.618034
# [1] 1.213412 1.213412
# [1] 0.381966 2.618034from scipy.optimize import root, fsolve
sol = root(F, np.array([3.0, 0.5])) # default method "hybr", finite-difference J
print(sol.x, sol.fun, sol.nfev, sol.success)
# [2.61803399 0.38196601] [-3.19744231e-14 2.37032616e-14] 12 True
print(sol.x - xstar)
# [ 1.32338585e-13 -5.73430192e-14]
sol = root(F, np.array([3.0, 0.5]), jac=J, tol=1e-14)
print(sol.x, sol.fun, sol.nfev, sol.njev)
# [2.61803399 0.38196601] [0. 0.] 12 1
print(sol.x - xstar)
# [ 4.44089210e-16 -5.55111512e-17]
for s in [[0.5, 3], [1, 1], [1, 0.2]]:
print(root(F, np.array(s, dtype=float)).x)
# [0.38196601 2.61803399]
# [1.21341166 1.21341166]
# [0.38196601 2.61803399]
print(fsolve(F, np.array([3.0, 0.5]))) # older interface, same algorithm
# [2.61803399 0.38196601]// rust/examples/newton_systems_c5.rs — cargo run --example newton_systems_c5
// C5: no library root finder in our crate list, so this is the hand-written
// Newton with a finite-difference Jacobian (what multiroot does by default),
// counting the evaluations of F.
use nalgebra::{DMatrix, DVector};
use std::cell::Cell;
const ALPHA: f64 = 3.0;
const N: f64 = 2.0;
// returns the path x_0, x_1, ...; None if J is exactly singular at some step
fn newton_sys(f: impl Fn(&DVector<f64>) -> DVector<f64>,
jac: impl Fn(&DVector<f64>) -> DMatrix<f64>,
x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<Vec<DVector<f64>>> {
let mut x = x0.clone();
let mut path = vec![x.clone()];
for _ in 0..maxit {
let delta = jac(&x).lu().solve(&(-f(&x)))?; // one linear solve per step
x += δ
path.push(x.clone());
if delta.norm() < tol { // norm() = sqrt(sum of squares)
return Some(path);
}
}
eprintln!("warning: no convergence");
Some(path)
}
fn v2(a: f64, b: f64) -> DVector<f64> { DVector::from_vec(vec![a, b]) }
fn fd_jacobian(f: impl Fn(&DVector<f64>) -> DVector<f64>, x: &DVector<f64>, h: f64) -> DMatrix<f64> {
let fx = f(x);
let mut jm = DMatrix::zeros(fx.len(), x.len());
for j in 0..x.len() {
let hj = h * x[j].abs().max(1.0);
let mut xh = x.clone();
xh[j] += hj;
jm.set_column(j, &((f(&xh) - &fx) / hj));
}
jm
}
fn main() {
let nfev = Cell::new(0); // a counter the closure may change
let f = |x: &DVector<f64>| {
nfev.set(nfev.get() + 1);
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(N)) - u,
ALPHA / (1.0 + u.powf(N)) - v])
};
let jfd = |x: &DVector<f64>| fd_jacobian(&f, x, f64::EPSILON.sqrt());
let xstar = v2((3.0 + 5f64.sqrt()) / 2.0, (3.0 - 5f64.sqrt()) / 2.0);
let p = newton_sys(&f, jfd, &v2(3.0, 0.5), 1e-12, 50).unwrap();
let x = p.last().unwrap();
println!("root {:?}, steps {}, F evaluations {}", x.as_slice(), p.len() - 1, nfev.get());
println!("residual {:?}", f(x).as_slice());
println!("error {:?}", (x - &xstar).as_slice());
for s in [[0.5, 3.0], [1.0, 1.0], [1.0, 0.2]] {
let p = newton_sys(&f, |x: &DVector<f64>| fd_jacobian(&f, x, 1.5e-8), &v2(s[0], s[1]), 1e-12, 50).unwrap();
println!("{:?}", p.last().unwrap().as_slice());
}
}
// Output:
// root [2.618033988749895, 0.3819660112501051], steps 6, F evaluations 24
// residual [4.440892098500626e-16, 5.551115123125783e-17]
// error [0.0, 0.0]
// [0.38196601125010515, 2.618033988749895]
// [1.2134116627622296, 1.2134116627622296]
// [0.38196601125010515, 2.618033988749895]With default settings, multiroot stops at a residual of about \(10^{-12}\) and an error of about \(5\times10^{-12}\); scipy.optimize.root at \(3\times10^{-14}\) and \(10^{-13}\). Both are fine for biology, but not “exact”: always look at f.root / .fun. With the exact Jacobian and a tight tolerance both reach the rounding level. The starts give the same roots as our own Newton, including “V on” from \((1, 0.2)\). The Rust run needs 4 evaluations of \(\mathbf F\) per step (one for \(\mathbf F(\mathbf x)\) in the Newton step, three for the Jacobian; reusing \(\mathbf F(\mathbf x)\) would save one).
C6.
# uses F(), J() from the Background; newton_sys() from the solution of C2
# (a) two nearby starts
for (s in list(c(1.9, 0.5), c(2.0, 0.55))) {
P <- newton_sys(F, J, s)
steps <- sqrt(rowSums(diff(P)^2))
cat("start", s, "| det J:", format(det(J(s)), digits = 3),
"| first step length:", format(steps[1], digits = 3),
"| min u, v on the way:", format(min(P), digits = 3),
"| end:", format(P[nrow(P), ], digits = 6), "\n")
}
# start 1.9 0.5 | det J: -0.0299 | first step length: 8.06 | min u, v on the way: -5.14 | end: 1.21341 1.21341
# start 2 0.55 | det J: 0.0663 | first step length: 3.42 | min u, v on the way: -0.891 | end: 2.618034 0.381966
# (b) Hill coefficient 2.5
n <- 2.5
x <- c(2, 0.5)
for (k in 1:2) {
x <- x + solve(J(x), -F(x))
print(x)
}
# [1] 9.722732 -3.246249
# [1] NaN NaN
# (c) damped Newton: halve the step until x stays >= 0 and ||F|| does not grow
newton_damped <- function(F, J, x, tol = 1e-12, maxit = 50) {
for (k in 1:maxit) {
delta <- solve(J(x), -F(x))
t <- 1
while (any(x + t * delta < 0) ||
sqrt(sum(F(x + t * delta)^2)) > sqrt(sum(F(x)^2))) {
t <- t / 2
if (t < 1e-10) stop("damping failed")
}
x <- x + t * delta
cat(k, t, format(x, digits = 10), "\n")
if (sqrt(sum((t * delta)^2)) < tol) return(x)
}
x
}
xd <- newton_damped(F, J, c(2, 0.5))
# 1 0.125 2.96534154158 0.03171888233
# 2 1 2.9931075381 0.1817681588
# 3 1 2.955241004 0.187230696
# 4 1 2.955096248 0.187363313
# 5 1 2.9550962031 0.1873633212
# 6 1 2.9550962031 0.1873633212
F(xd)
# [1] 0 0# uses F(), J() from the Background; newton_sys() from the solution of C2
# (a) two nearby starts
for s in [np.array([1.9, 0.5]), np.array([2.0, 0.55])]:
P = newton_sys(F, J, s)
steps = np.sqrt(np.sum(np.diff(P, axis=0)**2, axis=1))
print("start", s, f"| det J: {np.linalg.det(J(s)):.3g}",
f"| first step length: {steps[0]:.3g}",
f"| min u, v on the way: {P.min():.3g}", "| end:", P[-1].round(6))
# start [1.9 0.5] | det J: -0.0299 | first step length: 8.06 | min u, v on the way: -5.14 | end: [1.213412 1.213412]
# start [2. 0.55] | det J: 0.0663 | first step length: 3.42 | min u, v on the way: -0.891 | end: [2.618034 0.381966]
# (b) Hill coefficient 2.5
n = 2.5
x = np.array([2.0, 0.5])
for k in range(2):
x = x + np.linalg.solve(J(x), -F(x))
print(x)
# [ 9.72273233 -3.24624894]
# [nan nan]
# (c) damped Newton: halve the step until x stays >= 0 and ||F|| does not grow
def newton_damped(F, J, x, tol=1e-12, maxit=50):
for k in range(1, maxit + 1):
delta = np.linalg.solve(J(x), -F(x))
t = 1.0
while (np.any(x + t * delta < 0) or
np.linalg.norm(F(x + t * delta)) > np.linalg.norm(F(x))):
t = t / 2
if t < 1e-10:
raise RuntimeError("damping failed")
x = x + t * delta
print(k, t, x)
if np.linalg.norm(t * delta) < tol:
return x
return x
xd = newton_damped(F, J, np.array([2.0, 0.5]))
# 1 0.125 [2.96534154 0.03171888]
# 2 1.0 [2.99310754 0.18176816]
# 3 1.0 [2.955241 0.1872307]
# 4 1.0 [2.95509625 0.18736331]
# 5 1.0 [2.9550962 0.18736332]
# 6 1.0 [2.9550962 0.18736332]
print(F(xd))
# [0. 0.]// rust/examples/newton_systems_c6.rs — cargo run --example newton_systems_c6
// C6: failures (nearly singular J, NaN for a non-integer Hill coefficient)
// and a damped Newton that keeps concentrations non-negative.
use nalgebra::{DMatrix, DVector};
const ALPHA: f64 = 3.0;
// the Hill coefficient n is a parameter here, so we can change it
fn f(x: &DVector<f64>, n: f64) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![ALPHA / (1.0 + v.powf(n)) - u,
ALPHA / (1.0 + u.powf(n)) - v])
}
fn jac(x: &DVector<f64>, n: f64) -> DMatrix<f64> {
let (u, v) = (x[0], x[1]);
DMatrix::from_row_slice(2, 2, &[
-1.0, -ALPHA * n * v.powf(n - 1.0) / (1.0 + v.powf(n)).powi(2),
-ALPHA * n * u.powf(n - 1.0) / (1.0 + u.powf(n)).powi(2), -1.0])
}
// returns the path x_0, x_1, ...; None if J is exactly singular at some step
fn newton_sys(f: impl Fn(&DVector<f64>) -> DVector<f64>,
jac: impl Fn(&DVector<f64>) -> DMatrix<f64>,
x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<Vec<DVector<f64>>> {
let mut x = x0.clone();
let mut path = vec![x.clone()];
for _ in 0..maxit {
let delta = jac(&x).lu().solve(&(-f(&x)))?; // one linear solve per step
x += δ
path.push(x.clone());
if delta.norm() < tol { // norm() = sqrt(sum of squares)
return Some(path);
}
}
eprintln!("warning: no convergence");
Some(path)
}
fn v2(a: f64, b: f64) -> DVector<f64> { DVector::from_vec(vec![a, b]) }
fn newton_damped(n: f64, x0: &DVector<f64>, tol: f64, maxit: usize) -> DVector<f64> {
let mut x = x0.clone();
for k in 1..=maxit {
let delta = jac(&x, n).lu().solve(&(-f(&x, n))).expect("singular Jacobian");
let mut t = 1.0;
// halve the step until x stays >= 0 and ||F|| does not grow
loop {
let xt = &x + &delta * t;
if xt.iter().all(|&c| c >= 0.0) && f(&xt, n).norm() <= f(&x, n).norm() {
break;
}
t /= 2.0;
if t < 1e-10 { panic!("damping failed"); }
}
x += &delta * t;
println!("{} {} {:?}", k, t, x.as_slice());
if (&delta * t).norm() < tol { break; }
}
x
}
fn main() {
// (a) two nearby starts
for s in [[1.9, 0.5], [2.0, 0.55]] {
let x0 = v2(s[0], s[1]);
let p = newton_sys(|x: &DVector<f64>| f(x, 2.0), |x: &DVector<f64>| jac(x, 2.0), &x0, 1e-12, 50).unwrap();
let step1 = (&p[1] - &p[0]).norm();
let minval = p.iter().flat_map(|x| x.iter().copied()).fold(f64::INFINITY, f64::min);
let end = p.last().unwrap();
println!("start {:?} | det J: {:.3} | first step length: {:.3} | min u, v on the way: {:.3} | end: {:.6} {:.6}",
s, jac(&x0, 2.0).determinant(), step1, minval, end[0], end[1]);
}
// (b) Hill coefficient 2.5: plain Newton
let mut x = v2(2.0, 0.5);
for _ in 0..2 {
// with NaN entries the LU still "succeeds" and returns NaN
x += jac(&x, 2.5).lu().solve(&(-f(&x, 2.5))).unwrap();
println!("{:?}", x.as_slice());
}
// (c) damped Newton
let xd = newton_damped(2.5, &v2(2.0, 0.5), 1e-12, 50);
println!("{:?}", f(&xd, 2.5).as_slice());
}
// Output:
// start [1.9, 0.5] | det J: -0.030 | first step length: 8.057 | min u, v on the way: -5.136 | end: 1.213412 1.213412
// start [2.0, 0.55] | det J: 0.066 | first step length: 3.424 | min u, v on the way: -0.891 | end: 2.618034 0.381966
// [9.72273233260433, -3.2462489413408573]
// [NaN, NaN]
// 1 0.125 [2.9653415415755413, 0.03171888233239284]
// 2 1 [2.9931075381195704, 0.1817681588407846]
// 3 1 [2.955241004252892, 0.18723069602320588]
// 4 1 [2.9550962475008484, 0.1873633129788433]
// 5 1 [2.9550962031489827, 0.18736332124930322]
// 6 1 [2.9550962031489827, 0.1873633212493033]
// [0.0, 0.0]- At \((1.9, 0.5)\) the Jacobian is nearly singular (\(\det J = -0.03\)), the first step has length 8 and goes to \(u = -5.1\), and the run ends in the middle state. A start only \(0.1\) away, also with small \(\det J\), ends in “U on” after a detour through \(v = -0.89\). Near the curve \(\det J = 0\) the outcome is unpredictable.
- With \(n = 2.5\) the first step gives \(v = -3.25\), and \((-3.25)^{2.5}\) is
NaN; every later iterate isNaN. (Python also prints aRuntimeWarning: invalid value encountered in scalar power; R and Rust are silent.) - The damped Newton halves the first step three times (\(t = 0.125\)) to stay non-negative, then takes full steps and converges quadratically to the “U on” state of the \(n = 2.5\) switch, \((2.955096, 0.187363)\). Library routines use similar safeguards: scipy’s
hybruses a trust region, andmultiroot(F, c(2, 0.5), positive = TRUE)keeps the iterates non-negative and also finds \((2.955096, 0.187363)\) (withoutpositive = TRUEit warns “steady-state not reached”).
C7.
# uses F() from the Background; newton_sys() from the solution of C2
n <- 2 # back to n = 2 (C6 set n = 2.5)
g <- seq(0.25, 5, length.out = 8)
starts <- as.matrix(expand.grid(g, g)) # 64 starts
for (a in seq(1, 5, by = 0.5)) {
alpha <- a # F and J use the global alpha
out <- t(apply(starts, 1, function(s) {
P <- tryCatch(suppressWarnings(newton_sys(F, J, s)),
error = function(e) matrix(NA, 1, 2)) # singular J
c(P[nrow(P), ], nrow(P) - 1) # last iterate, number of steps
}))
ok <- apply(out[, 1:2], 1, function(x) all(is.finite(x)) && sqrt(sum(F(x)^2)) < 1e-10)
distinct <- unique(round(out[ok, 1:2, drop = FALSE], 6))
cat(sprintf("alpha = %.1f: %2d distinct roots; largest u = %.6f; %2d runs hit maxit\n",
a, nrow(distinct), max(distinct[, 1]), sum(out[, 3] == 50, na.rm = TRUE)))
}
# alpha = 1.0: 1 distinct roots; largest u = 0.682328; 0 runs hit maxit
# alpha = 1.5: 1 distinct roots; largest u = 0.861224; 0 runs hit maxit
# alpha = 2.0: 21 distinct roots; largest u = 1.000013; 52 runs hit maxit
# alpha = 2.5: 3 distinct roots; largest u = 2.000000; 0 runs hit maxit
# alpha = 3.0: 3 distinct roots; largest u = 2.618034; 0 runs hit maxit
# alpha = 3.5: 3 distinct roots; largest u = 3.186141; 0 runs hit maxit
# alpha = 4.0: 3 distinct roots; largest u = 3.732051; 0 runs hit maxit
# alpha = 4.5: 3 distinct roots; largest u = 4.265564; 0 runs hit maxit
# alpha = 5.0: 3 distinct roots; largest u = 4.791288; 0 runs hit maxit
(5 + sqrt(5^2 - 4)) / 2 # B5 formula at alpha = 5
# [1] 4.791288# uses F() from the Background; newton_sys() from the solution of C2
n = 2 # back to n = 2 (C6 set n = 2.5)
warnings.simplefilter("ignore") # we count non-converged runs instead
g = np.linspace(0.25, 5, 8)
starts = [np.array([u, v]) for v in g for u in g] # 64 starts
for a in np.arange(1, 5.01, 0.5):
alpha = a # F and J use the global alpha
roots, hit_maxit = [], 0
for s in starts:
try:
P = newton_sys(F, J, s)
except np.linalg.LinAlgError: # exactly singular Jacobian
continue
hit_maxit += (len(P) - 1 == 50)
x = P[-1]
if np.all(np.isfinite(x)) and np.linalg.norm(F(x)) < 1e-10:
roots.append(x)
distinct = np.unique(np.round(roots, 6), axis=0)
print(f"alpha = {a:.1f}: {len(distinct):2d} distinct roots; "
f"largest u = {distinct[:, 0].max():.6f}; {hit_maxit:2d} runs hit maxit")
# alpha = 1.0: 1 distinct roots; largest u = 0.682328; 0 runs hit maxit
# alpha = 1.5: 1 distinct roots; largest u = 0.861224; 0 runs hit maxit
# alpha = 2.0: 21 distinct roots; largest u = 1.000013; 54 runs hit maxit
# alpha = 2.5: 3 distinct roots; largest u = 2.000000; 0 runs hit maxit
# alpha = 3.0: 3 distinct roots; largest u = 2.618034; 0 runs hit maxit
# alpha = 3.5: 3 distinct roots; largest u = 3.186141; 0 runs hit maxit
# alpha = 4.0: 3 distinct roots; largest u = 3.732051; 0 runs hit maxit
# alpha = 4.5: 3 distinct roots; largest u = 4.265564; 0 runs hit maxit
# alpha = 5.0: 3 distinct roots; largest u = 4.791288; 0 runs hit maxit
print((5 + np.sqrt(5**2 - 4)) / 2) # B5 formula at alpha = 5
# 4.7912878474779195// rust/examples/newton_systems_c7.rs — cargo run --example newton_systems_c7
// C7: how many steady states for each promoter strength alpha?
use nalgebra::{DMatrix, DVector};
const N: f64 = 2.0;
fn f(x: &DVector<f64>, a: f64) -> DVector<f64> {
let (u, v) = (x[0], x[1]);
DVector::from_vec(vec![a / (1.0 + v.powf(N)) - u, a / (1.0 + u.powf(N)) - v])
}
fn jac(x: &DVector<f64>, a: f64) -> DMatrix<f64> {
let (u, v) = (x[0], x[1]);
DMatrix::from_row_slice(2, 2, &[
-1.0, -a * N * v.powf(N - 1.0) / (1.0 + v.powf(N)).powi(2),
-a * N * u.powf(N - 1.0) / (1.0 + u.powf(N)).powi(2), -1.0])
}
// last iterate and number of steps; None if J is exactly singular
fn newton_last(a: f64, x0: &DVector<f64>, tol: f64, maxit: usize) -> Option<(DVector<f64>, usize)> {
let mut x = x0.clone();
for k in 1..=maxit {
let delta = jac(&x, a).lu().solve(&(-f(&x, a)))?;
x += δ
if delta.norm() < tol { return Some((x, k)); }
}
Some((x, maxit))
}
fn main() {
let g: Vec<f64> = (0..8).map(|i| 0.25 + i as f64 * 4.75 / 7.0).collect();
for i in 0..9 {
let a = 1.0 + 0.5 * i as f64;
let mut distinct: Vec<[f64; 2]> = Vec::new();
let mut hit_maxit = 0;
for &v in &g {
for &u in &g {
let Some((x, k)) = newton_last(a, &DVector::from_vec(vec![u, v]), 1e-12, 50) else { continue };
if k == 50 { hit_maxit += 1; }
if x.iter().all(|c| c.is_finite()) && f(&x, a).norm() < 1e-10 {
let key = [(x[0] * 1e6).round() / 1e6, (x[1] * 1e6).round() / 1e6];
if !distinct.contains(&key) { distinct.push(key); }
}
}
}
let umax = distinct.iter().map(|k| k[0]).fold(f64::MIN, f64::max);
println!("alpha = {:.1}: {:2} distinct roots; largest u = {:.6}; {:2} runs hit maxit",
a, distinct.len(), umax, hit_maxit);
}
println!("{}", (5.0 + (5.0f64 * 5.0 - 4.0).sqrt()) / 2.0); // B5 formula at alpha = 5
}
// Output:
// alpha = 1.0: 1 distinct roots; largest u = 0.682328; 0 runs hit maxit
// alpha = 1.5: 1 distinct roots; largest u = 0.861224; 0 runs hit maxit
// alpha = 2.0: 19 distinct roots; largest u = 1.000011; 57 runs hit maxit
// alpha = 2.5: 3 distinct roots; largest u = 2.000000; 0 runs hit maxit
// alpha = 3.0: 3 distinct roots; largest u = 2.618034; 0 runs hit maxit
// alpha = 3.5: 3 distinct roots; largest u = 3.186141; 0 runs hit maxit
// alpha = 4.0: 3 distinct roots; largest u = 3.732051; 0 runs hit maxit
// alpha = 4.5: 3 distinct roots; largest u = 4.265564; 0 runs hit maxit
// alpha = 5.0: 3 distinct roots; largest u = 4.791288; 0 runs hit maxit
// 4.7912878474779195For \(\alpha \le 1.5\) there is one steady state, for \(\alpha \ge 2.5\) three, and the “U on” state matches \((\alpha + \sqrt{\alpha^2 - 4})/2\) (B5) to all printed digits. At \(\alpha = 2\) the three states merge at \((1, 1)\) and there \(\det J = 1 - 1 = 0\): the Jacobian is singular at the root. Newton then converges only linearly, most runs hit maxit, and the not-quite-converged iterates are “distinct” after rounding to 6 decimals, so the count (19–21, depending on the language’s rounding) is meaningless. This is the system version of a double root in one variable. The check: many runs at maxit, or a tiny \(\det J\) at the reported roots. At exactly such parameter values (bifurcations) the number of steady states changes, which is why they are worth locating.
Where this leads
- Gaussian elimination as LU (Part 3): what
solve(J, -F)does inside, why it costs about \(\tfrac23 n^3\) operations, and why we never formsolve(J). Pivoting, norms and conditioning: norms beyond the Euclidean length, and why a nearly singular \(J\) (C6) amplifies errors. - Structure: symmetric, banded, sparse (Part 3): sparse storage and sparse solvers. In a gene network each gene is regulated by a few others, so its Jacobian is sparse, and these solvers make Newton feasible for thousands of genes.
- Numerical differentiation (Part 7): central differences and Richardson extrapolation (what
numDerivdoes) for more accurate Jacobians. - Equilibria, stability and the phase plane (Part 8): the same toggle switch; the eigenvalues of \(J\) at each steady state decide which ones are stable, explaining why no cell sits in the middle state that Newton found so often.
- Gradient descent, Newton and quasi-Newton (Part 10): Newton applied to the gradient of a likelihood, with the Jacobian of the gradient (the Hessian); quasi-Newton methods build an approximate Jacobian cheaply, which C4 shows is enough.