Approach: use the nonparametric bootstrap to approximate the sampling distribution of the median. I'll implement the percentile bootstrap (simple and robust) and explain choice vs BCa. The function uses numpy for vectorized resampling and supports parallelism via joblib if needed (commented). It returns the (lower, upper) alpha-level CI.python
import numpy as np
def bootstrap_median_ci(data, n_bootstrap=10000, alpha=0.05, random_state=None):
"""
Compute bootstrap percentile CI for the median.
Returns (lower, upper).
"""
rng = np.random.default_rng(random_state)
data = np.asarray(data)
if data.size == 0:
raise ValueError("data must be non-empty")
# vectorized bootstrap: draw indices (n_bootstrap x n)
n = data.size
# Generate resample indices shape (n_bootstrap, n)
inds = rng.integers(0, n, size=(n_bootstrap, n))
resamples = data[inds]
medians = np.median(resamples, axis=1)
lower = np.quantile(medians, alpha/2)
upper = np.quantile(medians, 1 - alpha/2)
return float(lower), float(upper)
Why percentile vs BCa:- Percentile bootstrap is simple, fast, and often adequate for medians with moderate sample size.- BCa (bias-corrected and accelerated) adjusts for bias and skewness and gives more accurate coverage, especially for small samples or skewed distributions, but requires computing acceleration (jackknife) and extra statistics—more code and cost.Computational trade-offs and speedups:- Vectorize resampling with numpy as above to leverage C loops.- Reduce n_bootstrap (e.g., 2000) for exploratory work; increase for final estimates.- Use parallel processing (joblib or multiprocessing) to split bootstrap iterations.- Use subsampling or balanced bootstrap for huge n.- Use numba to JIT the loop if memory for full (n_bootstrap x n) array is too large.- For streaming/large n, perform online bootstrap: generate medians in chunks and aggregate quantiles.Complexity:- Time: O(n * n_bootstrap) for naive resampling; vectorized ops reduce Python overhead.- Space: O(n * n_bootstrap) if storing all resamples; you can compute medians in streaming/chunked fashion to reduce memory.Edge cases:- Very small n (n<5): BCa recommended.- Many ties: median sampling distribution discrete—interpret intervals accordingly.