By default, the appendix includes both code and its output. Setting show-output-results: false creates a code-only appendix—useful when output is lengthy, environment-specific, or simply not needed for reproduction.
This keeps the appendix compact and focused purely on source code.
extensions:regurgitate:show-output-results:false
Monte Carlo Simulation
We estimate π using random sampling—a classic demonstration of the Monte Carlo method:
import randomdef estimate_pi(n_points):"""Estimate pi using Monte Carlo simulation.""" inside_circle =0for _ inrange(n_points): x = random.uniform(-1, 1) y = random.uniform(-1, 1)if x**2+ y**2<=1: inside_circle +=1return4* inside_circle / n_pointsrandom.seed(42)estimates = [estimate_pi(10000) for _ inrange(5)]print("Pi estimates from 5 runs:")
Pi estimates from 5 runs:
for i, est inenumerate(estimates, 1):print(f" Run {i}: {est:.4f}")
Run 1: 3.1392
Run 2: 3.1552
Run 3: 3.1264
Run 4: 3.1064
Run 5: 3.1464
The appendix below contains only the source code—the printed output you see above is not duplicated there. This keeps the code reference clean and concise.
Code Appendix
extensions:regurgitate:show-output-results:false
import randomdef estimate_pi(n_points):"""Estimate pi using Monte Carlo simulation.""" inside_circle =0for _ inrange(n_points): x = random.uniform(-1, 1) y = random.uniform(-1, 1)if x**2+ y**2<=1: inside_circle +=1return4* inside_circle / n_pointsrandom.seed(42)estimates = [estimate_pi(10000) for _ inrange(5)]print("Pi estimates from 5 runs:")for i, est inenumerate(estimates, 1):print(f" Run {i}: {est:.4f}")print(f" Mean: {sum(estimates)/len(estimates):.4f}")print(f" Actual: {3.14159:.4f}")
# Bootstrap 95% CI for the mean of a sampleset.seed(123)original_sample <-c(12, 15, 14, 10, 13, 11, 16, 14, 15, 12)n_bootstrap <-1000boot_means <-replicate(n_bootstrap, { resample <-sample(original_sample, replace =TRUE)mean(resample)})ci <-quantile(boot_means, c(0.025, 0.975))cat("Original sample mean:", mean(original_sample), "\n")cat("95% Bootstrap CI: [", round(ci[1], 2), ",", round(ci[2], 2), "]\n")