Exercise: random numbers and Monte Carlo
Goal
By the end of this exercise you should be able to:
- explain why pseudo-random numbers are deterministic, run a toy generator by hand, and use seeds for reproducible simulations,
- turn uniform numbers into draws from another distribution by inverse-transform and rejection sampling,
- estimate an integral or a probability by Monte Carlo and report it with a standard error,
- read the \(1/\sqrt{N}\) law off a log–log plot and plan \(N\) for a target accuracy,
- recognise when the standard error cannot be trusted (infinite variance, rare events, bad importance weights),
- explain the curse of dimensionality and when Monte Carlo beats a grid,
- use importance sampling for a rare-event probability, and check it with the effective sample size,
- test whether motif hits are enriched in promoters by simulation, and compare with the exact answer.
The by-hand part uses pen, paper and a pocket calculator (for log and exp). The code part checks your hand answers and then works at sizes where only code works.
Background
Facts used below:
- Pseudo-random generators. A generator computes a long sequence of numbers from a seed by a fixed rule. A linear congruential generator (LCG) is \(x_{n+1} = (a x_n + c) \bmod m\), \(u_n = x_n/m\). The same seed gives the same sequence; the sequence repeats after at most \(m\) steps. Default generators: R, Mersenne Twister (
set.seed); numpy, PCG64 (np.random.default_rng); Rust,StdRng= ChaCha12 (rand). The three give different streams for the same seed. - Inverse transform. If \(U \sim \text{Uniform}(0,1)\) and \(F\) is a CDF, then \(X = F^{-1}(U)\) has CDF \(F\). Exponential with rate \(\lambda\): \(X = -\log(1 - U)/\lambda\) (or \(-\log(U)/\lambda\), since \(1-U\) is uniform too). Discrete: cut \([0, 1)\) at the cumulative probabilities and see where \(U\) falls.
- Rejection. To draw from a density \(f\) using a proposal \(g\) with \(f \le M g\): draw \(x \sim g\) and \(v \sim \text{Uniform}(0,1)\); keep \(x\) if \(v < f(x)/(M g(x))\). The acceptance rate is \(1/M\).
- Monte Carlo integration. \(\int_a^b f(x)\,dx = (b-a)\,\mathrm{E}[f(U)]\) with \(U \sim \text{Uniform}(a,b)\). With \(y_i = (b-a) f(U_i)\): \[\hat I = \bar y, \qquad \text{SE} = \frac{s}{\sqrt N}, \quad s = \text{sample sd of the } y_i.\] Report \(\hat I \pm 2\,\text{SE}\). A probability is the integral of an indicator: \(\hat p = k/N\), \(\text{SE} = \sqrt{\hat p(1-\hat p)/N}\).
- Error rate. The Monte Carlo error falls like \(N^{-1/2}\) in any dimension, if the variance of \(f(U)\) is finite. A grid rule of order \(p\) with \(N\) points in \(d\) dimensions has error about \(N^{-p/d}\).
- Importance sampling. \(\int h(x) f(x)\,dx = \mathrm{E}_g[h(X)\,w(X)]\), \(w = f/g\), \(X \sim g\). The proposal \(g\) must be positive wherever \(h f \neq 0\) and should have heavier tails than \(|h| f\). Effective sample size \(\text{ESS} = (\sum w_i)^2 / \sum w_i^2\).
A seeded generator and a Monte Carlo mean with its standard error, for \(\int_0^1 x^2\,dx = 1/3\). The numbers differ between the three languages (different generators); the estimates agree within their standard errors.
set.seed(42) # fix the stream
u <- runif(5) # 5 uniform numbers in (0, 1)
round(u, 4)
# [1] 0.9148 0.9371 0.2861 0.8304 0.6417
N <- 10000
fx <- runif(N)^2 # f(U) for f(x) = x^2 on [0, 1]
c(estimate = mean(fx), se = sd(fx) / sqrt(N)) # exact: 1/3
# estimate se
# 0.333355136 0.002989961 import numpy as np
rng = np.random.default_rng(42) # fix the stream
u = rng.random(5) # 5 uniform numbers in [0, 1)
print(np.round(u, 4))
# [0.774 0.4389 0.8586 0.6974 0.0942]
N = 10000
fx = rng.random(N)**2 # f(U) for f(x) = x^2 on [0, 1]
print(fx.mean(), fx.std(ddof=1) / np.sqrt(N)) # exact: 1/3
# 0.33010647737703147 0.0029719753378919327// rust/examples/monte_carlo_background.rs — cargo run --example monte_carlo_background
// Background: a seeded generator, uniform numbers, and a Monte Carlo mean with its SE.
use rand::{rngs::StdRng, RngExt, SeedableRng};
fn main() {
let mut rng = StdRng::seed_from_u64(42); // fix the stream
let u: Vec<f64> = (0..5).map(|_| rng.random::<f64>()).collect(); // uniform in [0, 1)
let rounded: Vec<f64> = u.iter().map(|v| (v * 1e4).round() / 1e4).collect();
println!("{:?}", rounded);
let n = 10000;
let fx: Vec<f64> = (0..n).map(|_| rng.random::<f64>().powi(2)).collect(); // f(U), f(x) = x^2
let mean = fx.iter().sum::<f64>() / n as f64;
let var = fx.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
println!("{} {}", mean, (var / n as f64).sqrt()); // exact: 1/3
}
// Output:
// [0.5266, 0.5427, 0.6365, 0.4059, 0.0343]
// 0.3334635029946159 0.0029601496657295544Rust prints numbers in its own format (e.g. 2.8665157188630015e-7 rather than 2.866516e-07). In Rust, rng.random::<f64>() and numpy’s rng.random() return numbers in \([0, 1)\), which can be 0; R’s runif never returns 0 or 1. That is why the Python and Rust code below use 1 - U inside a log.
By hand
B1. A toy generator. Use the LCG \(x_{n+1} = (5x_n + 1) \bmod 16\). (a) Starting from the seed \(x_1 = 1\), compute \(x_2, \dots, x_8\) and the corresponding \(u_n = x_n/16\). (b) Continue until the sequence repeats. What is the period? Which values of \(x\) appear? (c) Start instead from the seed 7. Where does this sequence join the one from (a)? (d) Change the multiplier to \(a = 4\) (seed 1). What happens? And with \(a = 3\), \(c = 0\) (seed 1)? (e) Someone reruns your simulation without setting the seed and gets a slightly different answer. Someone else reruns it with your seed in Python instead of R and also gets a different answer. Which of the two is a problem?
B2. Inverse transform. Waiting times between transcriptional bursts are exponential with rate \(\lambda = 0.5\) per hour. (a) Solve \(u = F(x) = 1 - e^{-\lambda x}\) for \(x\). (b) Turn the uniform numbers \(u = 0.3\), \(0.75\) and \(0.95\) into waiting times. (Useful: \(\ln 0.7 = -0.357\), \(\ln 0.25 = -1.386\), \(\ln 0.05 = -2.996\).) (c) Which \(u\) gives the median waiting time, and what is it? (d) A genome has base composition A 0.3, C 0.2, G 0.2, T 0.3. Write down the cut points in \([0, 1)\) and give the base for \(u = 0.45\), \(0.95\) and \(0.3\).
B3. Rejection sampling. Target: the Beta(2, 4) density \(f(x) = 20x(1-x)^3\) on \([0, 1]\); proposal: Uniform(0, 1). (a) Find the maximum of \(f\) (set \(f'(x) = 0\)). What is the smallest \(M\) you can use, and the acceptance rate? (b) For the pairs \((x, v) = (0.25, 0.9)\), \((0.8, 0.1)\), \((0.5, 0.5)\), decide whether \(x\) is accepted. (c) On average, how many proposals are needed for 1000 accepted draws? (d) What goes wrong if you take \(M = 1.5\) by mistake? Would the code warn you?
B4. Monte Carlo by hand. Estimate \(\int_0^1 x^2\,dx\) from the four uniform numbers \(0.1, 0.4, 0.7, 0.9\). (a) Compute the estimate, the sample sd \(s\) (divide by \(N-1\)) and the standard error. Is the true value \(1/3\) within \(\pm 2\) SE? (b) The true sd of \(U^2\) is \(\sqrt{1/5 - 1/9} = 0.298\). How many draws do you need for an SE of 0.001? (c) You have \(N = 10\,000\) and want the error 10 times smaller. How many draws do you need? And for the trapezoid rule (error \(\propto N^{-2}\))?
B5. The curse of dimensionality. (a) A grid with 10 points per axis: how many function evaluations in \(d = 1, 3, 6, 10\) dimensions? At 1 µs per evaluation, how long does each take? (b) With a budget of \(N = 10^6\) evaluations, how many grid points per axis can you afford in \(d = 2\), \(d = 6\) and \(d = 10\)? (c) A rule of order \(p\) has error \(\approx N^{-p/d}\); Monte Carlo has error \(\approx N^{-1/2}\). In which dimension do the two rates match for the trapezoid rule (\(p = 2\))? For Simpson’s rule (\(p = 4\))?
B6. Motif hits in promoters, exactly. A 1 Mb region (\(G = 10^6\) bp) has 50 non-overlapping promoters of 1000 bp, none at the ends. A motif hit is \(L = 10\) bp long; its start position is uniform on \(1, \dots, G - L + 1\). (a) For which start positions \(s\) does a hit overlap the promoter \([p, p + 999]\)? Compute the probability \(p_\text{hit}\) that one random hit overlaps any promoter. (b) With 200 independent hits, the number \(K\) of overlapping hits is Binomial\((200, p_\text{hit})\). Compute \(\mathrm{E}[K]\) and \(\mathrm{sd}(K)\). How many sd above the mean is the observed \(k = 18\)? (c) A simulation with \(B = 10\,000\) random placements found 122 with \(K \ge 18\). Give the simulated p-value, its SE, and the \((k+1)/(B+1)\) version. How large must \(B\) be for an SE of 10% of the p-value? (d) Name two features of real genomes that make the uniform, independent placement unrealistic. Why does that favour simulation over a formula?
B7. A rare event. A standardised motif score \(X\) of a random sequence is approximately \(N(0, 1)\); \(P(X > 5) = 2.87 \times 10^{-7}\). (a) With \(N = 10^5\) plain Monte Carlo draws, how many draws above 5 do you expect? What is the probability of seeing none? What do the estimate and its SE then say? (b) Importance sampling with proposal \(g = N(5, 1)\). Show that \(w(x) = \phi(x)/\phi(x - 5) = e^{12.5 - 5x}\), where \(\phi\) is the standard normal density. Evaluate \(w\) at \(x = 5\), \(5.5\), \(6\). (c) Four proposal draws are \(4.2, 5.1, 5.6, 6.3\). Compute \(h(x_i) w(x_i)\) with \(h(x) = 1\) if \(x > 5\), else 0, and the estimate. (Useful: \(e^{-13} = 2.26\times10^{-6}\), \(e^{-15.5} = 1.86\times10^{-7}\), \(e^{-19} = 5.6\times10^{-9}\).) (d) What fraction of the proposal draws fall above 5? Why does that help?
In code
C1. Generators and seeds. (a) Write lcg(n, seed, a, c, m) and check B1 (a), (b) and (d). (b) Implement RANDU: \(x_{n+1} = 65539\,x_n \bmod 2^{31}\), seed 1, \(u_n = x_n/2^{31}\). Draw 30 000 numbers and count the distinct values of \(9u_n - 6u_{n+1} + u_{n+2}\), rounded to 3 decimals. Do the same with your language’s default generator. What do you conclude? (c) Draw three uniforms twice with the same seed and check that they are identical. Compare the three numbers with those of a classmate who uses another language.
C2. Inverse-transform sampling. (a) Draw \(10^5\) burst waiting times with \(\lambda = 0.5\) per hour by inverse transform. Check the mean and sd (both \(1/\lambda = 2\)) and the fraction of waits longer than 6 h against \(e^{-3}\). (b) Draw \(10^5\) bases with the composition of B2(d) using the cumulative probabilities (findInterval; Python np.searchsorted). Check the frequencies.
C3. Rejection sampling. Write a rejection sampler for the Beta(2, 4) density of B3 with a uniform proposal. (a) With \(M = f(1/4)\) and with \(M = 10\): compare the acceptance rate with \(1/M\) and the mean of the accepted draws with \(1/3\). (b) Run it with \(M = 1.5\). What is the mean now? Compare with B3(d).
C4. Monte Carlo integration with an error bar. The OD curve \(N(t) = K/(1 + (K/N_0 - 1)e^{-rt})\), \(K = 1.2\), \(N_0 = 0.05\), \(r = 0.8\) per hour (the running example), has exact area \(\int_0^{10} N\,dt = \tfrac{K}{r}\log\frac{e^{10r} + K/N_0 - 1}{K/N_0} = 7.2444\). (a) Estimate the area from \(N = 1000\) uniform times, with SE and a \(\pm 2\) SE interval. Does it contain the exact value? (b) For \(N = 10^2, \dots, 10^5\), compute the root-mean-square error over 20 repeats, and the slope of \(\log(\text{RMS})\) against \(\log N\) (the lecture plots the same on log–log axes). (c) From the sample sd in (a), how many draws do you need for \(2\,\text{SE} = 0.01\)?
C5. When the error bar lies. Estimate \(\int_0^1 x^{-3/4}\,dx = 4\) and \(\int_0^1 x^{-1/4}\,dx = 4/3\) with \(N = 10^5\) draws, for seeds 1 to 5. Print each estimate with its SE. (a) For which integrand do the SEs agree between seeds, and is the truth within \(\pm 2\) SE? (b) Compute \(\int_0^1 (x^{-3/4})^2\,dx\) and \(\int_0^1 (x^{-1/4})^2\,dx\) by hand. What explains (a)?
C6. The curse of dimensionality. Toy marginal likelihood: \(d\) parameters with prior \(N(0, 1)\), one measurement \(y_i = 1\) each with noise sd 1, so \(Z = \phi(1; 0, \sqrt2)^d\) exactly. With a budget of \(10^5\) likelihood evaluations: (a) Grid: \(n = \lfloor 10^{5/d} \rfloor\) points per axis at the prior quantiles \(\Phi^{-1}((i - 0.5)/n)\), \(i = 1..n\) (qnorm; Python scipy.stats.norm.ppf), all \(n^d\) combinations, $Z = $ mean likelihood. (b) Monte Carlo: the same number \(n^d\) of draws from the prior. For \(d = 1, 2, 3, 4, 6, 8, 10\) print \(n\), \(n^d\), the relative errors of both, and the relative SE of Monte Carlo. Where is the crossover? Compare with B5(c). Compute the likelihood on the log scale and sum over parameters before exp.
C7. Motif hits in promoters, simulated. Set up the region of B6 (promoters start at \(10001, 30001, \dots\), every 20 000 bp). (a) Simulate \(B = 10\,000\) placements of 200 hits and count the overlaps each time. Compare the mean and variance of the counts with the binomial values. (b) Give the simulated p-value for \(k_\text{obs} = 18\) with SE and the \((k+1)/(B+1)\) version, and the exact value (pbinom; Python scipy.stats.binom.sf). (c) Repeat for \(k_\text{obs} = 25\). How reliable is the simulated p-value now?
C8. Importance sampling. (a) Estimate \(P(X > 5)\), \(X \sim N(0,1)\), with \(10^5\) plain draws and compare with the exact value (pnorm(5, lower.tail = FALSE); Python norm.sf(5)). (b) Use importance sampling with proposals \(N(3, 1)\), \(N(5, 1)\) and \(N(7, 1)\). Report each estimate with its relative SE. Which proposal is best, and why? (c) Failure: estimate \(\int \phi(x)\,dx = 1\) with \(w = \phi(x)/g(x)\) for proposals \(g = N(0, s^2)\) with \(s = 0.5, 1, 2, 5\). Print the estimate, SE, ESS and the largest weight’s share of the total. Which proposal is dangerous, and which number tells you?
Explore
The demo below runs Monte Carlo in your browser on three problems with a known answer: the area under the OD curve on \([0, 10]\) h (exact \(7.2444\), C4), the motif-overlap p-value \(P(K \ge 18)\) for 200 randomly placed hits (exact \(0.01314\), B6 and C7; each draw places 200 hits and counts the overlaps), and the rare-event probability \(P(X > 5)\) (exact \(2.867\times10^{-7}\), B7 and C8), plain or by importance sampling from \(N(5, 1)\). The buttons add draws to the running sample. Panel (a) shows the running estimate with its \(\pm 2\) SE band and the exact value; panel (b) shows the relative error of this run against \(N\) on log–log axes, with the dashed line \(\sigma/\sqrt N\) (the true SE, slope \(-\tfrac12\)). The second tab, Curse of dimensionality, is the toy marginal likelihood of C6: a grid at the prior quantiles against Monte Carlo with the same budget, and the number of evaluations each needs for 1 % error.
The demo uses its own seeded generator, so its numbers differ from those of R, Python and Rust in the solutions, but they agree within the standard errors. All numbers below are for seed 1; the draws come in the same order however you click, so the readout depends only on \(N\) and the seed.
E1. (the \(1/\sqrt N\) law) With OD-curve area, click +100 and write down the estimate, the SE and the error. Click +10 000 (\(N = 10\,100\)) and then +100 000 (\(N = 110\,100\)) and do the same. By what factor does the SE shrink per factor 100 in \(N\)? In panel (b), how do the error dots relate to the dashed line, and why do they scatter around it?
\(N = 100\): \(6.929 \pm 0.85\), SE \(0.426\), error \(-0.32\) (4.3 %). \(N = 10\,100\): \(7.230 \pm 0.083\), SE \(0.0415\), error \(-0.015\) (0.20 %). \(N = 110\,100\): \(7.232 \pm 0.025\), SE \(0.0125\), error \(-0.013\) (0.18 %). From \(N = 100\) to \(10\,100\) the SE falls by \(0.426/0.0415 = 10.3 \approx \sqrt{101}\): 100 times more draws for one more digit. The dots in panel (b) follow the dashed line \(\sigma/\sqrt N\) (\(\sigma = 4.16\)) with slope \(-\tfrac12\), but the actual error is random: whenever the running mean crosses the exact value the error dips far below the line, and it rarely stays far above it. At \(N = 10\,100\) the error is a third of an SE, at \(N = 110\,100\) about one SE, so it barely changed while the SE fell threefold. The SE describes the typical size of the error, not the error of one run.
E2. (is the error bar honest?) Stay with the OD-curve area. For seeds 1 to 10, move the seed slider and click +1000 once each time. Note the estimate and whether the exact value is inside \(\pm 2\) SE. How often does the band miss, and how often should it?
All ten SEs are about \(0.13\) (\(4.16/\sqrt{1000} = 0.132\)), so the band is \(\pm 0.26\) or \(\pm 0.27\) every time. The estimates are 7.141, 7.242, 7.320, 7.485, 6.989, 7.200, 7.554, 7.242, 7.287, 7.285. Only seed 7 misses: \(7.554 \pm 0.26\) ends at \(7.29\), just above the exact \(7.244\) (seeds 4 and 5 are close to the edge). A \(\pm 2\) SE band is a 95 % interval, so about 1 run in 20 should miss; 1 in 10 is within chance. This is why a single seed that “looks good” proves nothing, and why the SE, not the agreement of one run with a known answer, is what you report.
E3. (the motif test) Click motif overlap P(K ≥ 18), then +10 000. Compare the simulated p-value, its SE and the number of placements with \(K \ge 18\) with the lecture (122 of 10 000 in R) and with the exact \(0.01314\). What is the relative SE, and how many placements would you need for 10 % relative SE? Click +100 000 and check.
\(N = 10\,000\): 143 placements with \(K \ge 18\), estimate \(0.0143 \pm 0.0024\), SE \(0.00119\), error \(0.0012\) (8.8 %); the exact value is inside the band. R’s 122 and the demo’s 143 differ by \(0.0021\), less than 2 SE: two different streams, both honest. The relative SE is \(0.00119/0.0143 \approx 8\%\). For 10 % you need \(B \approx 100/p \approx 7\,600\) placements (B6c), so \(10\,000\) is already enough. At \(N = 110\,000\): 1 482 hits, \(0.01347 \pm 0.00070\), SE \(3.48\times10^{-4}\) (2.6 %): 11 times more draws, \(\sqrt{11} = 3.3\) times smaller SE.
E4. (rare event and importance sampling) Click rare event P(X > 5) with importance sampling off, then +100 000. What do the estimate, the SE and the readout say? Where are the error dots in panel (b), and where is the dashed line? Now tick importance sampling (this restarts the run), click +1000, then +100 000 (\(N = 101\,000\)). Read the estimate, the relative SE and the number of draws above 5.
Plain: 0 draws above 5, estimate \(0 \pm 0\), SE 0, error 100 %; the readout warns that SE = 0 claims certainty. In panel (b) the error is stuck at 1 (100 %) for every \(N\), and the dashed true SE \(\sqrt{p(1-p)}/(p\sqrt N)\) lies above it (5.9 at \(N = 10^5\)): the true uncertainty is larger than the answer, but the sample cannot show it. With importance sampling: at \(N = 1000\), 509 draws above 5 and \(2.69\times10^{-7} \pm 4.1\times10^{-8}\) (SE 7.7 %); at \(N = 101\,000\), 50 582 draws above 5 and \(2.878\times10^{-7} \pm 4.3\times10^{-9}\), relative SE \(0.75\%\), error \(0.39\%\), as in the lecture. The relative sd of one draw drops from \(\sqrt{(1-p)/p} = 1868\) to \(2.38\): the variance falls by a factor \((1868/2.38)^2 \approx 6\times10^5\), so plain Monte Carlo would need about 600 000 times more draws for the same SE.
E5. (the curse of dimensionality) Open Curse of dimensionality (budget \(10^5\), seed 1). Move \(d\) from 1 to 10 and read the grid error, the expected Monte Carlo SE and the error of the Monte Carlo run. Where does Monte Carlo start to win? Then read panel (d) and the second readout line at \(d = 10\) and \(d = 20\): how many evaluations does each method need for 1 % error, and how long is that at 1 µs per evaluation?
Grid errors: \(< 10^{-8}\) (\(d = 1\)), 0.016 % (\(d = 2\)), 0.49 % (\(d = 3\)), 2.8 % (\(d = 4\)), 18 % (\(d = 6\)), 78 % (\(d = 10\), 3 points per axis), the numbers of C6. The expected Monte Carlo SE grows only slowly: 0.19 %, 0.29 %, 0.39 %, 0.50 %, 0.74 %, 1.5 %; the seed-1 run has error 1.2 % at \(d = 10\). The grid wins at \(d = 1, 2\), the two are level at \(d = 3\), and Monte Carlo wins from \(d = 4\), as B5(c) predicted for a second-order rule. For 1 % at \(d = 10\) the grid needs 65 points per axis, about \(10^{18}\) evaluations (43 000 years), Monte Carlo 213 110 draws (0.2 s). At \(d = 20\): grid 101 per axis, \(10^{40}\) evaluations (far beyond the age of the universe); Monte Carlo about 5 million draws (5 s). Monte Carlo’s cost also grows with \(d\), like \(1.364^d\), because the likelihood becomes more peaked relative to the prior, but exponentially more slowly than the grid’s.
Hints
%% in R and % in Python and Rust are “mod” (the remainder after division). In R: set.seed, runif, identical. In Python: rng = np.random.default_rng(seed), then rng.random(n), rng.integers, rng.normal. In Rust: StdRng::seed_from_u64(seed) and rng.random::<f64>() from rand, normal draws with rand_distr::StandardNormal. For RANDU, \(65539 x\) stays below \(2^{53}\), so doubles (R) are exact; Python integers are always exact.
Set \(u = F(x)\) and solve for \(x\): take logs. The cut points for the bases are \(0, 0.3, 0.5, 0.7, 1\); a \(u\) exactly on a cut point goes to the interval that starts there. For rejection, \(f'(x) = 20(1-x)^2(1 - 4x)\). Compare R’s rexp and sample (with prob =); Python rng.exponential(scale = 1/lam) and rng.choice(bases, p = prob).
SE \(= s/\sqrt N\), so to make the SE \(c\) times smaller you need \(c^2\) times more draws. To reach a target SE \(\delta\): \(N = (s/\delta)^2\). Sample sd: R sd (divides by \(N-1\)), Python x.std(ddof=1) (numpy’s default ddof=0 divides by \(N\)). For the slope: R coef(lm(log(rms) ~ log(N))), Python np.polyfit(np.log(N), np.log(rms), 1). Repeat runs with replicate in R or a list comprehension in Python.
\(N^{-p/d} = N^{-1/2}\) when \(p/d = 1/2\). For the grid in R: expand.grid(rep(list(nodes), d)) builds all combinations; in Python itertools.product(nodes, repeat=d); in Rust, write grid point \(k\) in base \(n\): its \(j\)-th digit is the index of the node on axis \(j\). Store parameters as a \(d \times N\) matrix and use colSums(dnorm(y, th, 1, log = TRUE)) (Python norm.logpdf(...).sum(axis=0)), so the product of \(d\) small numbers does not underflow.
A hit \([s, s + 9]\) overlaps \([p, p + 999]\) when \(s + 9 \ge p\) and \(s \le p + 999\). To test many hits at once against sorted, non-overlapping promoters: find the last promoter that starts at or before the hit’s end (R findInterval; Python np.searchsorted(pstart, s + L - 1, side="right"); Rust pstart.partition_point(|&p| p <= s + L - 1)), then check that it has not ended before the hit starts. Draw starts with sample.int(G - L + 1, n, replace = TRUE) (Python rng.integers(1, G - L + 2, n); the upper end is excluded). pbinom(k - 1, n, p, lower.tail = FALSE) is \(P(K \ge k)\); in statrs, Binomial::sf(k - 1).
\(\phi(x) = e^{-x^2/2}/\sqrt{2\pi}\), so \(\phi(x)/\phi(x - 5) = \exp\!\big(-\tfrac{x^2}{2} + \tfrac{(x-5)^2}{2}\big)\); expand the square. In R, dnorm(x, mean, sd) and pnorm; in Python, scipy.stats.norm.pdf and norm.sf; in Rust, write the density yourself and use statrs::distribution::Normal for sf. The ESS is between 1 (one weight dominates) and \(N\) (all weights equal).
Solutions
B1. (a) \(x\): 1, 6, 15, 12, 13, 2, 11, 8 (\(5 \cdot 1 + 1 = 6\); \(5 \cdot 6 + 1 = 31 = 16 + 15\); \(5\cdot 15 + 1 = 76 = 4\cdot16 + 12\); …). \(u\): 0.0625, 0.375, 0.9375, 0.75, 0.8125, 0.125, 0.6875, 0.5. (b) Continuing: 9, 14, 7, 4, 5, 10, 3, 0, then 1 again. Period 16: every value \(0, \dots, 15\) appears exactly once per cycle (full period). (c) 7 → 4 → 5 → 10 → …: the seed 7 is just a different starting point on the same cycle (7 follows 14 in (b)). (d) \(a = 4\): 1, 5, 5, 5, … (\(4 \cdot 5 + 1 = 21 = 16 + 5\)): stuck at a fixed point after one step. \(a = 3\), \(c = 0\): 1, 3, 9, 11, 1, …: period 4. Only special choices of \(a\), \(c\), \(m\) give a full period. (e) Neither is an error: both reruns use other random numbers, so the answers should differ by about the Monte Carlo error. It becomes a problem only if the difference is larger than the error bars, or if the first person cannot reproduce your exact numbers when checking your code (then they need your seed and your software).
B2. (a) \(1 - u = e^{-\lambda x}\), so \(x = -\log(1-u)/\lambda\). (b) \(x = -2\ln(1 - u)\): \(u = 0.3 \to -2\ln 0.7 = 0.713\) h; \(u = 0.75 \to -2\ln 0.25 = 2.773\) h; \(u = 0.95 \to -2\ln 0.05 = 5.991\) h (the arrows in the lecture figure). (c) \(u = 0.5\): \(x = 2\ln 2 = 1.386\) h, below the mean of 2 h (the exponential is skewed). (d) Cut points \(0, 0.3, 0.5, 0.7, 1\): A \(= [0, 0.3)\), C \(= [0.3, 0.5)\), G \(= [0.5, 0.7)\), T \(= [0.7, 1)\). \(u = 0.45 \to\) C, \(0.95 \to\) T, \(0.3 \to\) C.
B3. (a) \(f'(x) = 20(1-x)^2(1-4x) = 0\) at \(x = 1/4\): \(M = f(1/4) = 20 \cdot 0.25 \cdot 0.75^3 = 2.109\). Acceptance rate \(1/M = 0.474\). (b) \((0.25, 0.9)\): \(f/M = 1 > 0.9\), accept. \((0.8, 0.1)\): \(f(0.8) = 20\cdot0.8\cdot0.2^3 = 0.128\), \(f/M = 0.061 < 0.1\), reject. \((0.5, 0.5)\): \(f(0.5) = 1.25\), \(f/M = 0.593 > 0.5\), accept. (c) About \(1000 M = 2109\) proposals. (d) Near the mode, \(f(x) > 1.5\), so \(f/M > 1\) and every proposal there is accepted, but not as often as it should be: the peak is cut off, and the sample comes from \(\min(f, M)\) normalised, not from \(f\). No warning: the code runs and returns wrong draws. C3(b) shows the bias in the mean.
B4. (a) \(f = 0.01, 0.16, 0.49, 0.81\); estimate \(1.47/4 = 0.3675\). Deviations \(-0.3575, -0.2075, 0.1225, 0.4425\); \(s^2 = 0.38168/3 = 0.1272\), \(s = 0.357\); SE \(= 0.357/2 = 0.178\). The error \(0.034\) is well inside \(\pm 2\,\text{SE} = \pm 0.357\) (a very wide interval: 4 draws say little). (b) \(N = (0.298/0.001)^2 \approx 89\,000\). (c) 100 times more: \(10^6\). Trapezoid: error \(\propto N^{-2}\), so \(\sqrt{10} \approx 3.2\) times more points.
B5. (a) \(10, 10^3, 10^6, 10^{10}\) evaluations: 10 µs, 1 ms, 1 s, \(10^4\) s \(\approx\) 2.8 hours. (b) \(d = 2\): \(\sqrt{10^6} = 1000\). \(d = 6\): \(10^{6/6} = 10\). \(d = 10\): \(10^{0.6} = 3.98\), so 3 points (\(4^{10} = 1\,048\,576 > 10^6\)). (c) \(p/d = 1/2\): \(d = 4\) for the trapezoid rule, \(d = 8\) for Simpson. Above that, the grid’s error falls more slowly than Monte Carlo’s.
B6. (a) Overlap when \(p - 9 \le s \le p + 999\): \(1009\) start positions per promoter. There are \(G - L + 1 = 999\,991\) possible starts, so \(p_\text{hit} = 50 \cdot 1009 / 999\,991 = 0.05045\) (the promoters are far apart, so the windows do not overlap). (b) \(\mathrm{E}[K] = 200 \cdot 0.05045 = 10.09\); \(\mathrm{sd}(K) = \sqrt{200 \cdot 0.05045 \cdot 0.94955} = 3.095\). \((18 - 10.09)/3.095 = 2.56\) sd above the mean. (c) \(\hat p = 122/10\,000 = 0.0122\); SE \(= \sqrt{0.0122 \cdot 0.9878 / 10\,000} = 0.0011\); \((k+1)/(B+1) = 123/10\,001 = 0.0123\). For SE \(= 0.1 p\): \(\sqrt{p(1-p)/B} = 0.1p \Rightarrow B = (1-p)/(0.01 p) \approx 8100\). In general \(B \approx 100/p\): you need about 100 simulations as extreme as the data. (d) For example: assembly gaps and unmappable repeats (no peak can be called there); GC content and chromatin accessibility vary along the genome (motifs and peaks are not uniform); peaks cannot overlap each other; promoters may overlap or sit at the region ends. Each changes \(p_\text{hit}\) or breaks independence. A simulation only needs a way to draw placements under the null (shuffle within accessible, GC-matched regions), not a formula for the distribution of \(K\).
B7. (a) \(10^5 \cdot 2.87\times10^{-7} = 0.029\) hits expected; \(P(\text{none}) = e^{-0.029} = 0.97\). Then \(\hat p = 0\) and SE \(= 0\): the method reports “exactly zero, with no uncertainty”, which is wrong. (b) \(-\tfrac{x^2}{2} + \tfrac{(x-5)^2}{2} = -\tfrac{x^2}{2} + \tfrac{x^2 - 10x + 25}{2} = 12.5 - 5x\). \(w(5) = e^{-12.5} = 3.7\times10^{-6}\), \(w(5.5) = e^{-15} = 3.1\times10^{-7}\), \(w(6) = e^{-17.5} = 2.5\times10^{-8}\). (c) \(h w = 0\), \(e^{-13} = 2.26\times10^{-6}\), \(e^{-15.5} = 1.86\times10^{-7}\), \(e^{-19} = 5.6\times10^{-9}\); estimate \(= (0 + 2.26\times10^{-6} + 1.86\times10^{-7} + 5.6\times10^{-9})/4 = 6.1\times10^{-7}\). The right order of magnitude from only 4 draws (plain Monte Carlo would need millions to see a single hit). (d) Half (the proposal is centred at 5). Every draw above 5 contributes a small, similar weight, instead of almost all draws contributing 0 and a rare draw contributing 1.
C1.
lcg <- function(n, seed, a = 5, c = 1, m = 16) {
x <- numeric(n); x[1] <- seed
for (i in 2:n) x[i] <- (a * x[i - 1] + c) %% m
x
}
lcg(17, seed = 1)
# [1] 1 6 15 12 13 2 11 8 9 14 7 4 5 10 3 0 1
lcg(6, seed = 1, a = 4)
# [1] 1 5 5 5 5 5
randu <- function(n, seed = 1) {
x <- numeric(n); x[1] <- seed
for (i in 2:n) x[i] <- (65539 * x[i - 1]) %% 2^31
x / 2^31
}
u <- randu(30000)
v <- 9 * u[1:29998] - 6 * u[2:29999] + u[3:30000]
length(unique(round(v, 3))) # distinct values (3 decimals)
# [1] 15
set.seed(1); w <- runif(30000)
v <- 9 * w[1:29998] - 6 * w[2:29999] + w[3:30000]
length(unique(round(v, 3)))
# [1] 11531
set.seed(42); a <- runif(3)
set.seed(42); b <- runif(3)
identical(a, b)
# [1] TRUEimport numpy as np
def lcg(n, seed, a=5, c=1, m=16):
x = [seed]
for i in range(n - 1):
x.append((a * x[-1] + c) % m)
return x
print(lcg(17, seed=1))
# [1, 6, 15, 12, 13, 2, 11, 8, 9, 14, 7, 4, 5, 10, 3, 0, 1]
print(lcg(6, seed=1, a=4))
# [1, 5, 5, 5, 5, 5]
def randu(n, seed=1):
x = [seed]
for i in range(n - 1):
x.append((65539 * x[-1]) % 2**31) # Python ints: exact
return np.array(x) / 2**31
u = randu(30000)
v = 9 * u[:-2] - 6 * u[1:-1] + u[2:]
print(len(np.unique(np.round(v, 3)))) # distinct values (3 decimals)
# 15
w = np.random.default_rng(1).random(30000)
v = 9 * w[:-2] - 6 * w[1:-1] + w[2:]
print(len(np.unique(np.round(v, 3))))
# 11400
a = np.random.default_rng(42).random(3)
b = np.random.default_rng(42).random(3)
print(np.array_equal(a, b))
# True// rust/examples/monte_carlo_c1.rs — cargo run --example monte_carlo_c1
// C1: a toy LCG, the RANDU planes, and reproducible seeds.
use rand::{rngs::StdRng, RngExt, SeedableRng};
use std::collections::HashSet;
fn lcg(n: usize, seed: u64, a: u64, c: u64, m: u64) -> Vec<u64> {
let mut x = vec![seed];
for _ in 1..n {
let last = *x.last().unwrap();
x.push((a * last + c) % m);
}
x
}
fn n_distinct(v: &[f64]) -> usize {
// distinct values after rounding to 3 decimals
let set: HashSet<i64> = v.iter().map(|x| (x * 1000.0).round() as i64).collect();
set.len()
}
fn main() {
println!("{:?}", lcg(17, 1, 5, 1, 16));
println!("{:?}", lcg(6, 1, 4, 1, 16));
// RANDU: x_{n+1} = 65539 x_n mod 2^31 (u64 arithmetic is exact here)
let u: Vec<f64> = lcg(30000, 1, 65539, 0, 1 << 31)
.iter().map(|&x| x as f64 / 2f64.powi(31)).collect();
let v: Vec<f64> = (0..29998).map(|i| 9.0 * u[i] - 6.0 * u[i + 1] + u[i + 2]).collect();
println!("{}", n_distinct(&v));
let mut rng = StdRng::seed_from_u64(1);
let w: Vec<f64> = (0..30000).map(|_| rng.random::<f64>()).collect();
let v: Vec<f64> = (0..29998).map(|i| 9.0 * w[i] - 6.0 * w[i + 1] + w[i + 2]).collect();
println!("{}", n_distinct(&v));
let mut r1 = StdRng::seed_from_u64(42);
let mut r2 = StdRng::seed_from_u64(42);
let a: Vec<f64> = (0..3).map(|_| r1.random::<f64>()).collect();
let b: Vec<f64> = (0..3).map(|_| r2.random::<f64>()).collect();
println!("{}", a == b);
}
// Output:
// [1, 6, 15, 12, 13, 2, 11, 8, 9, 14, 7, 4, 5, 10, 3, 0, 1]
// [1, 5, 5, 5, 5, 5]
// 15
// 11441
// true- reproduces B1. (b) RANDU’s combination takes only 15 distinct values (the whole numbers \(-5, \dots, 9\)): every triple lies on one of 15 planes in the unit cube. For a good generator it takes more than 11 000 different values. (c) Same seed, same numbers in one language; the three languages give different numbers for seed 42 (see the Background example: R 0.9148, 0.9371, 0.2861; numpy 0.7740, 0.4389, 0.8586; Rust 0.5266, 0.5427, 0.6365).
C2.
set.seed(1)
lambda <- 0.5
x <- -log(runif(1e5)) / lambda
c(mean = mean(x), sd = sd(x), p6 = mean(x > 6), exact_p6 = exp(-lambda * 6))
# mean sd p6 exact_p6
# 2.00769570 2.01138431 0.05068000 0.04978707
prob <- c(A = 0.3, C = 0.2, G = 0.2, T = 0.3)
b <- names(prob)[findInterval(runif(1e5), c(0, cumsum(prob)))]
round(table(b) / 1e5, 3)
# b
# A C G T
# 0.300 0.198 0.203 0.299 import numpy as np
rng = np.random.default_rng(1)
lam = 0.5
x = -np.log(1 - rng.random(100000)) / lam # numpy's random() can return 0, never 1
print(x.mean(), x.std(ddof=1), np.mean(x > 6), np.exp(-lam * 6))
# 1.9989637824174569 1.9928150385548216 0.0489 0.049787068367863944
bases = np.array(["A", "C", "G", "T"])
prob = np.array([0.3, 0.2, 0.2, 0.3])
idx = np.searchsorted(np.cumsum(prob), rng.random(100000), side="right")
b = bases[idx]
for base in bases:
print(base, round(np.mean(b == base), 3))
# A 0.3
# C 0.201
# G 0.2
# T 0.299// rust/examples/monte_carlo_c2.rs — cargo run --example monte_carlo_c2
// C2: inverse-transform sampling, continuous (exponential) and discrete (bases).
use rand::{rngs::StdRng, RngExt, SeedableRng};
fn main() {
let mut rng = StdRng::seed_from_u64(1);
let lambda = 0.5;
let n = 100000;
// random::<f64>() is in [0, 1): use 1 - U so the log never sees 0
let x: Vec<f64> = (0..n).map(|_| -(1.0 - rng.random::<f64>()).ln() / lambda).collect();
let mean = x.iter().sum::<f64>() / n as f64;
let sd = (x.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt();
let p6 = x.iter().filter(|&&v| v > 6.0).count() as f64 / n as f64;
println!("{} {} {} {}", mean, sd, p6, (-lambda * 6.0).exp());
let bases = ['A', 'C', 'G', 'T'];
let cum = [0.3, 0.5, 0.7, 1.0]; // cumulative probabilities
let mut counts = [0usize; 4];
for _ in 0..n {
let u = rng.random::<f64>();
let k = cum.partition_point(|&c| c <= u); // first k with cum[k] > u
counts[k] += 1;
}
for k in 0..4 {
println!("{} {:.3}", bases[k], counts[k] as f64 / n as f64);
}
}
// Output:
// 2.014590172571388 2.011585421715309 0.0514 0.049787068367863944
// A 0.298
// C 0.200
// G 0.201
// T 0.301Mean and sd are both close to 2, and \(P(X > 6)\) is close to \(e^{-3} = 0.0498\); the differences are Monte Carlo error (SE of a proportion near 0.05 with \(N = 10^5\) is 0.0007). The base frequencies match the composition to within about 0.002.
C3.
f <- function(x) 20 * x * (1 - x)^3
rejection <- function(n, M) {
x <- runif(n)
keep <- runif(n) < f(x) / M
list(rate = mean(keep), x = x[keep])
}
set.seed(1)
for (M in c(f(1/4), 10)) {
r <- rejection(1e5, M)
cat(sprintf("M = %6.3f acceptance %.4f (1/M = %.4f) mean %.4f\n",
M, r$rate, 1 / M, mean(r$x)))
}
# M = 2.109 acceptance 0.4738 (1/M = 0.4741) mean 0.3338
# M = 10.000 acceptance 0.1018 (1/M = 0.1000) mean 0.3346
r <- rejection(1e5, 1.5) # M too small: f > M near the mode
mean(r$x)
# [1] 0.3428292import numpy as np
def f(x):
return 20 * x * (1 - x)**3
rng = np.random.default_rng(1)
def rejection(n, M):
x = rng.random(n)
keep = rng.random(n) < f(x) / M
return keep.mean(), x[keep]
for M in [f(0.25), 10]:
rate, x = rejection(100000, M)
print(f"M = {M:6.3f} acceptance {rate:.4f} (1/M = {1 / M:.4f}) mean {x.mean():.4f}")
# M = 2.109 acceptance 0.4744 (1/M = 0.4741) mean 0.3332
# M = 10.000 acceptance 0.1005 (1/M = 0.1000) mean 0.3294
rate, x = rejection(100000, 1.5) # M too small
print(x.mean())
# 0.3438341745510367// rust/examples/monte_carlo_c3.rs — cargo run --example monte_carlo_c3
// C3: rejection sampling from Beta(2, 4) with a uniform proposal.
use rand::{rngs::StdRng, RngExt, SeedableRng};
fn f(x: f64) -> f64 {
20.0 * x * (1.0 - x).powi(3)
}
// returns (acceptance rate, accepted draws)
fn rejection(n: usize, m: f64, rng: &mut StdRng) -> (f64, Vec<f64>) {
let mut acc = Vec::new();
for _ in 0..n {
let x = rng.random::<f64>();
if rng.random::<f64>() < f(x) / m {
acc.push(x);
}
}
(acc.len() as f64 / n as f64, acc)
}
fn mean(v: &[f64]) -> f64 {
v.iter().sum::<f64>() / v.len() as f64
}
fn main() {
let mut rng = StdRng::seed_from_u64(1);
for m in [f(0.25), 10.0] {
let (rate, x) = rejection(100000, m, &mut rng);
println!("M = {:6.3} acceptance {:.4} (1/M = {:.4}) mean {:.4}", m, rate, 1.0 / m, mean(&x));
}
let (_, x) = rejection(100000, 1.5, &mut rng); // M too small
println!("{}", mean(&x));
}
// Output:
// M = 2.109 acceptance 0.4738 (1/M = 0.4741) mean 0.3346
// M = 10.000 acceptance 0.1010 (1/M = 0.1000) mean 0.3319
// 0.34408071455438727The acceptance rates match \(1/M\), and with a valid \(M\) the mean is \(1/3\) within Monte Carlo error. A larger \(M\) (10) is still correct, only wasteful: 90% of proposals are rejected. With \(M = 1.5 < \max f\) the mean is 0.343–0.344 in all three languages, more than 10 SE above \(1/3\) (SE about 0.0007): the sampler is biased, silently (B3(d)).
C4.
K <- 1.2; N0 <- 0.05; r <- 0.8
od <- function(t) K / (1 + (K / N0 - 1) * exp(-r * t))
exact <- K / r * log((exp(r * 10) + K / N0 - 1) / (K / N0))
set.seed(1)
fx <- 10 * od(runif(1000, 0, 10))
est <- mean(fx); se <- sd(fx) / sqrt(1000)
c(estimate = est, se = se, lower = est - 2 * se, upper = est + 2 * se, exact = exact)
# estimate se lower upper exact
# 7.2188630 0.1306143 6.9576343 7.4800916 7.2444483
Ns <- 10^(2:5)
rms <- sapply(Ns, function(N)
sqrt(mean(replicate(20, 10 * mean(od(runif(N, 0, 10))) - exact)^2)))
signif(rms, 3)
# [1] 0.4240 0.1440 0.0522 0.0122
coef(lm(log(rms) ~ log(Ns)))[2] # slope
# log(Ns)
# -0.5064274
s <- sd(fx)
ceiling((2 * s / 0.01)^2) # N for 2 SE = 0.01
# [1] 682405import numpy as np
K, N0, r = 1.2, 0.05, 0.8
def od(t):
return K / (1 + (K / N0 - 1) * np.exp(-r * t))
exact = K / r * np.log((np.exp(r * 10) + K / N0 - 1) / (K / N0))
rng = np.random.default_rng(1)
fx = 10 * od(rng.uniform(0, 10, 1000))
est, se = fx.mean(), fx.std(ddof=1) / np.sqrt(1000)
print(est, se, est - 2 * se, est + 2 * se, exact)
# 7.23270830213515 0.13148444515414026 6.96973941182687 7.495677192443431 7.244448295149627
Ns = 10.0**np.arange(2, 6)
rms = np.array([np.sqrt(np.mean([(10 * od(rng.uniform(0, 10, int(N))).mean() - exact)**2
for _ in range(20)])) for N in Ns])
print(np.round(rms, 4))
# [0.3398 0.1324 0.0473 0.0109]
print(np.polyfit(np.log(Ns), np.log(rms), 1)[0]) # slope
# -0.4924279626433256
s = fx.std(ddof=1)
print(int(np.ceil((2 * s / 0.01)**2))) # N for 2 SE = 0.01
# 691527// rust/examples/monte_carlo_c4.rs — cargo run --release --example monte_carlo_c4
// C4: Monte Carlo AUC of the logistic OD curve, its SE, and the 1/sqrt(N) law.
use rand::{rngs::StdRng, RngExt, SeedableRng};
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 mean_sd(v: &[f64]) -> (f64, f64) {
let n = v.len() as f64;
let m = v.iter().sum::<f64>() / n;
(m, (v.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0)).sqrt())
}
fn main() {
let exact = K / R * (((R * 10.0).exp() + K / N0 - 1.0) / (K / N0)).ln();
let mut rng = StdRng::seed_from_u64(1);
let fx: Vec<f64> = (0..1000).map(|_| 10.0 * od(rng.random_range(0.0..10.0))).collect();
let (est, s) = mean_sd(&fx);
let se = s / 1000f64.sqrt();
println!("{} {} {} {} {}", est, se, est - 2.0 * se, est + 2.0 * se, exact);
let ns = [1e2, 1e3, 1e4, 1e5];
let mut rms = Vec::new();
for &n in &ns {
let mut sq = 0.0;
for _ in 0..20 {
let est: f64 = (0..n as usize).map(|_| 10.0 * od(rng.random_range(0.0..10.0))).sum::<f64>() / n;
sq += (est - exact).powi(2);
}
rms.push((sq / 20.0).sqrt());
}
println!("{:.4?}", rms);
// least-squares slope of log(rms) against log(N)
let lx: Vec<f64> = ns.iter().map(|n| n.ln()).collect();
let ly: Vec<f64> = rms.iter().map(|e| e.ln()).collect();
let (mx, my) = (lx.iter().sum::<f64>() / 4.0, ly.iter().sum::<f64>() / 4.0);
let slope = lx.iter().zip(&ly).map(|(x, y)| (x - mx) * (y - my)).sum::<f64>()
/ lx.iter().map(|x| (x - mx).powi(2)).sum::<f64>();
println!("{}", slope);
println!("{}", (2.0 * s / 0.01).powi(2).ceil()); // N for 2 SE = 0.01
}
// Output:
// 7.1492276443540135 0.13236669661937034 6.884494251115273 7.413961037592754 7.244448295149627
// [0.3480, 0.1071, 0.0401, 0.0145]
// -0.45649196538764913
// 700838The interval contains 7.2444 in all three languages. The RMS error falls by about \(\sqrt{10} = 3.2\) per factor 10 in \(N\); the fitted slopes (\(-0.51\), \(-0.49\), \(-0.46\)) are close to \(-1/2\) (20 repeats give a noisy RMS, hence the spread). An accuracy of \(\pm 0.01\) needs about 700 000 draws; integrate (R) or scipy.integrate.quad reach \(10^{-6}\) with 21 evaluations. In one dimension, quadrature wins by far.
C5.
for (seed in 1:5) {
set.seed(seed)
x <- runif(1e5)
fa <- x^(-0.75) # exact integral 4, infinite variance
fb <- x^(-0.25) # exact integral 4/3, finite variance
cat(sprintf("seed %d x^-0.75: %.4f (se %.4f) x^-0.25: %.5f (se %.5f)\n",
seed, mean(fa), sd(fa) / sqrt(1e5), mean(fb), sd(fb) / sqrt(1e5)))
}
# seed 1 x^-0.75: 3.9829 (se 0.1597) x^-0.25: 1.33521 (se 0.00150)
# seed 2 x^-0.75: 3.7502 (se 0.0787) x^-0.25: 1.33254 (se 0.00146)
# seed 3 x^-0.75: 4.1278 (se 0.3577) x^-0.25: 1.33514 (se 0.00151)
# seed 4 x^-0.75: 3.8487 (se 0.1098) x^-0.25: 1.33280 (se 0.00148)
# seed 5 x^-0.75: 4.3530 (se 0.3693) x^-0.25: 1.33695 (se 0.00154)import numpy as np
for seed in range(1, 6):
x = np.random.default_rng(seed).random(100000)
fa = x**-0.75 # exact integral 4, infinite variance
fb = x**-0.25 # exact integral 4/3, finite variance
sa, sb = fa.std(ddof=1) / np.sqrt(1e5), fb.std(ddof=1) / np.sqrt(1e5)
print(f"seed {seed} x^-0.75: {fa.mean():.4f} (se {sa:.4f}) x^-0.25: {fb.mean():.5f} (se {sb:.5f})")
# seed 1 x^-0.75: 4.3893 (se 0.4061) x^-0.25: 1.33418 (se 0.00154)
# seed 2 x^-0.75: 3.7834 (se 0.1006) x^-0.25: 1.33259 (se 0.00147)
# seed 3 x^-0.75: 4.1233 (se 0.1560) x^-0.25: 1.33605 (se 0.00153)
# seed 4 x^-0.75: 4.1846 (se 0.2683) x^-0.25: 1.33355 (se 0.00152)
# seed 5 x^-0.75: 3.9657 (se 0.2581) x^-0.25: 1.33296 (se 0.00149)// rust/examples/monte_carlo_c5.rs — cargo run --example monte_carlo_c5
// C5: finite vs infinite variance; the SE is only trustworthy for the first.
use rand::{rngs::StdRng, RngExt, SeedableRng};
fn mean_se(v: &[f64]) -> (f64, f64) {
let n = v.len() as f64;
let m = v.iter().sum::<f64>() / n;
let var = v.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0);
(m, (var / n).sqrt())
}
fn main() {
for seed in 1..=5 {
let mut rng = StdRng::seed_from_u64(seed);
// 1 - U is in (0, 1], so x^-0.75 never divides by 0
let x: Vec<f64> = (0..100000).map(|_| 1.0 - rng.random::<f64>()).collect();
let fa: Vec<f64> = x.iter().map(|v| v.powf(-0.75)).collect(); // exact 4
let fb: Vec<f64> = x.iter().map(|v| v.powf(-0.25)).collect(); // exact 4/3
let (ma, sa) = mean_se(&fa);
let (mb, sb) = mean_se(&fb);
println!("seed {} x^-0.75: {:.4} (se {:.4}) x^-0.25: {:.5} (se {:.5})", seed, ma, sa, mb, sb);
}
}
// Output:
// seed 1 x^-0.75: 3.8874 (se 0.1133) x^-0.25: 1.33630 (se 0.00149)
// seed 2 x^-0.75: 3.9980 (se 0.1431) x^-0.25: 1.33461 (se 0.00151)
// seed 3 x^-0.75: 4.1596 (se 0.3187) x^-0.25: 1.33322 (se 0.00151)
// seed 4 x^-0.75: 3.9976 (se 0.1784) x^-0.25: 1.33362 (se 0.00151)
// seed 5 x^-0.75: 4.5185 (se 0.6564) x^-0.25: 1.33595 (se 0.00155)- For \(x^{-1/4}\) the SEs agree (0.0015) and the estimates are within \(\pm 2\) SE of \(4/3\). For \(x^{-3/4}\) the SE changes by a factor of up to 6 between seeds, and several estimates miss 4 by more than 2 SE (R seed 2: \(3.75 \pm 0.079\), 3 SE off).
- \(\int_0^1 x^{-3/2}\,dx = \infty\) and \(\int_0^1 x^{-1/2}\,dx = 2\). The variance of \(x^{-3/4}\) is infinite, so the CLT and the formula SE \(= s/\sqrt N\) do not apply: the rare draws very close to 0 make the estimate jump, and the sample sd is usually too small. The variance of \(x^{-1/4}\) is \(2 - (4/3)^2 = 0.22\), finite. The fix here is a change of variables \(x = v^4\), which turns the integral into \(\int_0^1 4\,dv\).
C6.
lik <- function(th, y) exp(colSums(dnorm(y, th, sd = 1, log = TRUE))) # th: d x N
compare <- function(d, budget = 1e5) {
y <- rep(1, d)
Z <- dnorm(1, 0, sqrt(2))^d
n <- floor(budget^(1 / d) + 1e-9) # grid points per axis
nodes <- qnorm((1:n - 0.5) / n)
grid <- t(as.matrix(expand.grid(rep(list(nodes), d))))
N <- ncol(grid)
L <- lik(matrix(rnorm(d * N), nrow = d), y)
c(d = d, n = n, N = N, grid_err = abs(mean(lik(grid, y)) / Z - 1),
mc_err = abs(mean(L) / Z - 1), mc_relse = sd(L) / sqrt(N) / mean(L))
}
set.seed(1)
round(t(sapply(c(1, 2, 3, 4, 6, 8, 10), compare)), 4)
# d n N grid_err mc_err mc_relse
# [1,] 1 100000 100000 0.0000 0.0013 0.0019
# [2,] 2 316 99856 0.0002 0.0021 0.0029
# [3,] 3 46 97336 0.0049 0.0029 0.0040
# [4,] 4 17 83521 0.0282 0.0068 0.0054
# [5,] 6 6 46656 0.1770 0.0009 0.0109
# [6,] 8 4 65536 0.4121 0.0117 0.0129
# [7,] 10 3 59049 0.7823 0.0017 0.0186import itertools
import numpy as np
from scipy.stats import norm
def lik(th, y): # th: d x N
return np.exp(norm.logpdf(y[:, None], th, 1).sum(axis=0))
def compare(d, rng, budget=1e5):
y = np.ones(d)
Z = norm.pdf(1, 0, np.sqrt(2))**d
n = int(np.floor(budget**(1 / d) + 1e-9))
nodes = norm.ppf((np.arange(1, n + 1) - 0.5) / n)
grid = np.array(list(itertools.product(nodes, repeat=d))).T
N = grid.shape[1]
L = lik(rng.standard_normal((d, N)), y)
return [d, n, N, abs(lik(grid, y).mean() / Z - 1), abs(L.mean() / Z - 1),
L.std(ddof=1) / np.sqrt(N) / L.mean()]
rng = np.random.default_rng(1)
print(" d n N grid_err mc_err mc_relse")
# d n N grid_err mc_err mc_relse
for d in [1, 2, 3, 4, 6, 8, 10]:
r = compare(d, rng)
print(f"{r[0]:4d} {r[1]:7d} {r[2]:7d} {r[3]:9.4f} {r[4]:8.4f} {r[5]:8.4f}")
# 1 100000 100000 0.0000 0.0026 0.0019
# 2 316 99856 0.0002 0.0012 0.0029
# 3 46 97336 0.0049 0.0070 0.0040
# 4 17 83521 0.0282 0.0016 0.0054
# 6 6 46656 0.1770 0.0029 0.0108
# 8 4 65536 0.4121 0.0224 0.0129
# 10 3 59049 0.7823 0.0066 0.0187// rust/examples/monte_carlo_c6.rs — cargo run --release --example monte_carlo_c6
// C6: the curse of dimensionality. Marginal likelihood Z in d dimensions,
// grid (n points per axis at prior quantiles) vs Monte Carlo from the prior.
use rand::{rngs::StdRng, RngExt, SeedableRng};
use rand_distr::StandardNormal;
use statrs::distribution::{ContinuousCDF, Normal};
fn log_dnorm(x: f64, mu: f64, sd: f64) -> f64 {
-0.5 * ((x - mu) / sd).powi(2) - sd.ln() - 0.5 * (2.0 * std::f64::consts::PI).ln()
}
// likelihood of y_i = 1 (noise sd 1) at one parameter vector th
fn lik(th: &[f64]) -> f64 {
th.iter().map(|&t| log_dnorm(1.0, t, 1.0)).sum::<f64>().exp()
}
fn main() {
let std_normal = Normal::new(0.0, 1.0).unwrap();
let mut rng = StdRng::seed_from_u64(1);
println!(" d n N grid_err mc_err mc_relse");
for d in [1usize, 2, 3, 4, 6, 8, 10] {
let z = log_dnorm(1.0, 0.0, 2f64.sqrt()).exp().powi(d as i32);
let n = (1e5f64.powf(1.0 / d as f64) + 1e-9).floor() as usize;
let nodes: Vec<f64> = (1..=n).map(|i| std_normal.inverse_cdf((i as f64 - 0.5) / n as f64)).collect();
let big_n = n.pow(d as u32);
// grid: decode point index k into d digits in base n
let mut th = vec![0.0; d];
let mut grid_sum = 0.0;
for k in 0..big_n {
let mut q = k;
for j in 0..d {
th[j] = nodes[q % n];
q /= n;
}
grid_sum += lik(&th);
}
// Monte Carlo with the same number of points
let l: Vec<f64> = (0..big_n).map(|_| {
let th: Vec<f64> = (0..d).map(|_| rng.sample::<f64, _>(StandardNormal)).collect();
lik(&th)
}).collect();
let m = l.iter().sum::<f64>() / big_n as f64;
let s = (l.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (big_n - 1) as f64).sqrt();
println!("{:4} {:7} {:7} {:9.4} {:8.4} {:8.4}", d, n, big_n,
(grid_sum / big_n as f64 / z - 1.0).abs(), (m / z - 1.0).abs(),
s / (big_n as f64).sqrt() / m);
}
}
// Output:
// d n N grid_err mc_err mc_relse
// 1 100000 100000 0.0000 0.0031 0.0019
// 2 316 99856 0.0002 0.0037 0.0029
// 3 46 97336 0.0049 0.0016 0.0040
// 4 17 83521 0.0282 0.0071 0.0054
// 6 6 46656 0.1770 0.0065 0.0108
// 8 4 65536 0.4121 0.0210 0.0130
// 10 3 59049 0.7823 0.0267 0.0194All three languages give the same grid errors (no random numbers there). The grid is far better in \(d = 1, 2\), the two are similar at \(d = 3\), and from \(d = 4\) the grid is worse; at \(d = 10\) it has 3 points per axis and is 78% wrong, while Monte Carlo is within about 3%. This matches B5(c) (\(d = 4\) for a second-order rule). The relative SE of Monte Carlo grows with \(d\) too (from 0.002 to 0.019), but slowly: the variance of the likelihood under the prior grows like \(1.36^d\).
C7.
G <- 1e6; L <- 10
pstart <- seq(10001, by = 20000, length.out = 50)
pend <- pstart + 999
n_hits <- 200
p <- 50 * (1000 + L - 1) / (G - L + 1)
overlaps <- function(s) {
i <- findInterval(s + L - 1, pstart)
i > 0 & pend[pmax(i, 1)] >= s
}
set.seed(1)
B <- 10000
K <- replicate(B, sum(overlaps(sample.int(G - L + 1, n_hits, replace = TRUE))))
for (k_obs in c(18, 25)) {
k <- sum(K >= k_obs)
cat(sprintf("k_obs %d: simulated %d of %d, p = %.5f (se %.5f), (k+1)/(B+1) = %.5f, exact %.3g\n",
k_obs, k, B, k / B, sqrt(k / B * (1 - k / B) / B), (k + 1) / (B + 1),
pbinom(k_obs - 1, n_hits, p, lower.tail = FALSE)))
}
# k_obs 18: simulated 122 of 10000, p = 0.01220 (se 0.00110), (k+1)/(B+1) = 0.01230, exact 0.0131
# k_obs 25: simulated 1 of 10000, p = 0.00010 (se 0.00010), (k+1)/(B+1) = 0.00020, exact 3.02e-05
c(mean(K), n_hits * p, var(K), n_hits * p * (1 - p))
# [1] 10.059500 10.090091 9.678528 9.581041import numpy as np
from scipy.stats import binom
G, L = 10**6, 10
pstart = np.arange(50) * 20000 + 10001
pend = pstart + 999
n_hits = 200
p = 50 * (1000 + L - 1) / (G - L + 1)
def overlaps(s):
i = np.searchsorted(pstart, s + L - 1, side="right") # like findInterval
return (i > 0) & (pend[np.maximum(i, 1) - 1] >= s)
rng = np.random.default_rng(1)
B = 10000
K = np.array([overlaps(rng.integers(1, G - L + 2, n_hits)).sum() for _ in range(B)])
for k_obs in [18, 25]:
k = np.sum(K >= k_obs)
print(f"k_obs {k_obs}: simulated {k} of {B}, p = {k / B:.5f} (se {np.sqrt(k / B * (1 - k / B) / B):.5f}), "
f"(k+1)/(B+1) = {(k + 1) / (B + 1):.5f}, exact {binom.sf(k_obs - 1, n_hits, p):.3g}")
# k_obs 18: simulated 119 of 10000, p = 0.01190 (se 0.00108), (k+1)/(B+1) = 0.01200, exact 0.0131
# k_obs 25: simulated 0 of 10000, p = 0.00000 (se 0.00000), (k+1)/(B+1) = 0.00010, exact 3.02e-05
print(K.mean(), n_hits * p, K.var(ddof=1), n_hits * p * (1 - p))
# 10.0555 10.090090810817296 9.478367586758678 9.581041147964598// rust/examples/monte_carlo_c7.rs — cargo run --release --example monte_carlo_c7
// C7: motif hits in promoters, simulated (permutation-style) vs exact binomial.
use rand::{rngs::StdRng, RngExt, SeedableRng};
use statrs::distribution::{Binomial, DiscreteCDF};
fn main() {
let (g, l) = (1_000_000u64, 10u64);
let pstart: Vec<u64> = (0..50).map(|j| 10001 + 20000 * j).collect();
let pend: Vec<u64> = pstart.iter().map(|s| s + 999).collect();
let n_hits = 200u64;
let p = 50.0 * (1000 + l - 1) as f64 / (g - l + 1) as f64;
// does a hit starting at s overlap a promoter?
let overlaps = |s: u64| -> bool {
let i = pstart.partition_point(|&ps| ps <= s + l - 1); // like findInterval
i > 0 && pend[i - 1] >= s
};
let mut rng = StdRng::seed_from_u64(1);
let b = 10000;
let k: Vec<u64> = (0..b).map(|_| {
(0..n_hits).filter(|_| overlaps(rng.random_range(1..=g - l + 1))).count() as u64
}).collect();
let binom = Binomial::new(p, n_hits).unwrap();
for k_obs in [18u64, 25] {
let c = k.iter().filter(|&&x| x >= k_obs).count();
let ph = c as f64 / b as f64;
println!("k_obs {}: simulated {} of {}, p = {:.5} (se {:.5}), (k+1)/(B+1) = {:.5}, exact {:.3e}",
k_obs, c, b, ph, (ph * (1.0 - ph) / b as f64).sqrt(),
(c + 1) as f64 / (b + 1) as f64, binom.sf(k_obs - 1)); // sf(x) = P(K > x)
}
let m = k.iter().sum::<u64>() as f64 / b as f64;
let v = k.iter().map(|&x| (x as f64 - m).powi(2)).sum::<f64>() / (b - 1) as f64;
println!("{} {} {} {}", m, n_hits as f64 * p, v, n_hits as f64 * p * (1.0 - p));
}
// Output:
// k_obs 18: simulated 130 of 10000, p = 0.01300 (se 0.00113), (k+1)/(B+1) = 0.01310, exact 1.314e-2
// k_obs 25: simulated 1 of 10000, p = 0.00010 (se 0.00010), (k+1)/(B+1) = 0.00020, exact 3.017e-5
// 10.0433 10.090090810817296 9.495174627462335 9.581041147964598- The mean and variance of the simulated counts agree with the binomial \(10.09\) and \(9.58\) within simulation noise: a check that the simulation code implements the intended null model. (b) The simulated p-values (0.0122, 0.0119, 0.0130) are within about 1 SE of the exact 0.0131. (c) For \(k_\text{obs} = 25\) the exact p-value is \(3.0\times10^{-5}\); with \(B = 10\,000\) we expect 0.3 simulations that extreme and see 0 or 1. The estimate is either 0 or 3 times too large, and its SE is as large as the estimate. All we can honestly say is \(p \lesssim 2\times10^{-4}\). A precise small p-value needs \(B \approx 100/p \approx 3\times10^6\) placements, or importance sampling (C8).
C8.
ess <- function(w) sum(w)^2 / sum(w^2)
N <- 1e5
set.seed(1)
z <- rnorm(N)
c(plain = mean(z > 5), exact = pnorm(5, lower.tail = FALSE))
# plain exact
# 0.000000e+00 2.866516e-07
for (mu in c(3, 5, 7)) {
x <- rnorm(N, mean = mu)
hw <- (x > 5) * dnorm(x) / dnorm(x, mean = mu)
cat(sprintf("proposal N(%d, 1): estimate %.4e relative se %.4f\n",
mu, mean(hw), sd(hw) / sqrt(N) / mean(hw)))
}
# proposal N(3, 1): estimate 2.8729e-07 relative se 0.0243
# proposal N(5, 1): estimate 2.9074e-07 relative se 0.0075
# proposal N(7, 1): estimate 2.8786e-07 relative se 0.0200
for (s in c(0.5, 1, 2, 5)) {
x <- rnorm(N, sd = s)
w <- dnorm(x) / dnorm(x, sd = s)
cat(sprintf("proposal sd %.1f: estimate %.4f se %.4f ESS %6.0f max share %.5f\n",
s, mean(w), sd(w) / sqrt(N), ess(w), max(w) / sum(w)))
}
# proposal sd 0.5: estimate 0.9881 se 0.0250 ESS 1538 max share 0.02277
# proposal sd 1.0: estimate 1.0000 se 0.0000 ESS 100000 max share 0.00001
# proposal sd 2.0: estimate 1.0020 se 0.0023 ESS 66197 max share 0.00002
# proposal sd 5.0: estimate 0.9962 se 0.0051 ESS 27944 max share 0.00005import numpy as np
from scipy.stats import norm
def ess(w):
return w.sum()**2 / np.sum(w**2)
N = 100000
rng = np.random.default_rng(1)
z = rng.standard_normal(N)
print(np.mean(z > 5), norm.sf(5))
# 0.0 2.866515718791933e-07
for mu in [3, 5, 7]:
x = rng.normal(mu, 1, N)
hw = (x > 5) * norm.pdf(x) / norm.pdf(x, mu)
print(f"proposal N({mu}, 1): estimate {hw.mean():.4e} relative se {hw.std(ddof=1) / np.sqrt(N) / hw.mean():.4f}")
# proposal N(3, 1): estimate 2.8545e-07 relative se 0.0247
# proposal N(5, 1): estimate 2.8648e-07 relative se 0.0075
# proposal N(7, 1): estimate 2.8304e-07 relative se 0.0205
for s in [0.5, 1, 2, 5]:
x = rng.normal(0, s, N)
w = norm.pdf(x) / norm.pdf(x, 0, s)
print(f"proposal sd {s:.1f}: estimate {w.mean():.4f} se {w.std(ddof=1) / np.sqrt(N):.4f} "
f"ESS {ess(w):6.0f} max share {w.max() / w.sum():.5f}")
# proposal sd 0.5: estimate 0.9819 se 0.0134 ESS 5086 max share 0.00783
# proposal sd 1.0: estimate 1.0000 se 0.0000 ESS 100000 max share 0.00001
# proposal sd 2.0: estimate 0.9996 se 0.0023 ESS 66104 max share 0.00002
# proposal sd 5.0: estimate 1.0083 se 0.0051 ESS 28210 max share 0.00005// rust/examples/monte_carlo_c8.rs — cargo run --release --example monte_carlo_c8
// C8: importance sampling for a rare event, and a proposal that is too narrow.
use rand::{rngs::StdRng, RngExt, SeedableRng};
use rand_distr::StandardNormal;
use statrs::distribution::{ContinuousCDF, Normal};
fn dnorm(x: f64, mu: f64, sd: f64) -> f64 {
(-0.5 * ((x - mu) / sd).powi(2)).exp() / (sd * (2.0 * std::f64::consts::PI).sqrt())
}
fn mean_sd(v: &[f64]) -> (f64, f64) {
let n = v.len() as f64;
let m = v.iter().sum::<f64>() / n;
(m, (v.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (n - 1.0)).sqrt())
}
fn main() {
let n = 100000;
let sqn = (n as f64).sqrt();
let mut rng = StdRng::seed_from_u64(1);
let mut z = || -> f64 { rng.sample(StandardNormal) };
let hits = (0..n).filter(|_| z() > 5.0).count();
println!("{} {:e}", hits as f64 / n as f64, Normal::new(0.0, 1.0).unwrap().sf(5.0));
for mu in [3.0, 5.0, 7.0] {
let hw: Vec<f64> = (0..n).map(|_| {
let x = mu + z();
if x > 5.0 { dnorm(x, 0.0, 1.0) / dnorm(x, mu, 1.0) } else { 0.0 }
}).collect();
let (m, s) = mean_sd(&hw);
println!("proposal N({}, 1): estimate {:.4e} relative se {:.4}", mu, m, s / sqn / m);
}
for sd in [0.5, 1.0, 2.0, 5.0] {
let w: Vec<f64> = (0..n).map(|_| { let x = sd * z(); dnorm(x, 0.0, 1.0) / dnorm(x, 0.0, sd) }).collect();
let (m, s) = mean_sd(&w);
let sum: f64 = w.iter().sum();
let ess = sum * sum / w.iter().map(|x| x * x).sum::<f64>();
let maxw = w.iter().cloned().fold(0.0, f64::max);
println!("proposal sd {:.1}: estimate {:.4} se {:.4} ESS {:6.0} max share {:.5}",
sd, m, s / sqn, ess, maxw / sum);
}
}
// Output:
// 0 2.8665157188630015e-7
// proposal N(3, 1): estimate 2.8957e-7 relative se 0.0243
// proposal N(5, 1): estimate 2.8805e-7 relative se 0.0075
// proposal N(7, 1): estimate 2.7420e-7 relative se 0.0203
// proposal sd 0.5: estimate 0.9574 se 0.0082 ESS 11983 max share 0.00273
// proposal sd 1.0: estimate 1.0000 se 0.0000 ESS 100000 max share 0.00001
// proposal sd 2.0: estimate 1.0016 se 0.0023 ESS 66152 max share 0.00002
// proposal sd 5.0: estimate 0.9977 se 0.0051 ESS 27954 max share 0.00005- Plain Monte Carlo sees no draw above 5 and reports 0. (b) All three proposals agree with the exact value to within about 2 SE; \(N(5, 1)\) has the smallest relative SE (0.75%), because it puts half of the draws above 5 where \(\phi\) is largest. \(N(7, 1)\) puts most draws far out, where the target is tiny, and \(N(3, 1)\) wastes most draws below 5. (c) \(s = 1\) is the target itself (all weights 1, SE 0). \(s = 2\) and \(s = 5\) are wider: honest SEs, ESS 66 000 and 28 000. \(s = 0.5\) has lighter tails than the target, and the weights \(\phi(x)/g(x) \propto e^{1.5x^2}\) have infinite variance: in Rust the estimate is \(0.957 \pm 0.008\), more than 5 SE below the truth. The warning signs are the ESS (1 500 to 12 000 of 100 000, and very different between languages) and a largest weight carrying up to 2% of the total.
Where this leads
- Stochastic simulation (Part 8): Gillespie’s algorithm draws exponential waiting times by inverse transform (C2) and chooses the next reaction by the discrete inverse transform of B2(d). Averages over simulated cells are Monte Carlo estimates with standard errors.
- Stochastic differential equations (Part 9): expectations over SDE paths have two errors, the step size (bias) and the Monte Carlo error \(\propto 1/\sqrt N\); \(h\) and \(N\) are chosen together.
- Identifiability and uncertainty of fitted parameters (Part 10): standard errors and profile likelihoods give uncertainty for fitted parameters. The alternative it mentions, the bootstrap (refit to many resampled data sets), is again a Monte Carlo average.
- Not covered in this course: Markov chain Monte Carlo (MCMC), which samples from a posterior when even importance sampling fails in high dimensions, and quasi-Monte Carlo (low-discrepancy points), which beats \(1/\sqrt N\) for smooth integrands in moderate dimension.