Bootstrap Confidence Interval for Mean Order Value
Statistics & ExperimentsModel answerLast updated
Implement vectorized bootstrap resampling to estimate a 95% confidence interval for the mean of a sample, handling memory constraints efficiently.
You're analyzing transaction data for an online retailer. Given a single sample of historical order amounts, you need to estimate the uncertainty around the average order value.
Write a Python function that computes a 95% confidence interval for the mean using bootstrap resampling with 10,000 iterations.
Input:
orders: a NumPy array or list of numeric order values (floats or integers)
Output:
- A tuple
(lower_bound, upper_bound)representing the 95% confidence interval
Requirements:
- Use the percentile method: the interval should span the 2.5th to 97.5th percentiles of the bootstrap distribution
- Each bootstrap sample should be the same size as the original data, drawn with replacement
- Optimize for performance: the solution should handle arrays with tens of thousands of elements without excessive memory usage
- Handle edge cases appropriately (empty arrays, invalid values, etc.)
Example:
orders = [45.2, 67.8, 23.1, 89.4, 56.7, ...] # thousands of values
lower, upper = compute_bootstrap_ci(orders)
# Returns something like (52.3, 58.9)
Explain your approach, including how you handle the memory/performance tradeoff and any assumptions you make.
Hints
Hint 1
Bootstrap resampling means drawing n samples with replacement from your n observations, computing the statistic of interest, and repeating many times to build an empirical distribution
Hint 2
Vectorize the resampling step using NumPy's random integer generation and fancy indexing rather than Python loops—but watch out for memory when creating a 10,000 × n matrix
Hint 3
Process resamples in chunks to bound memory usage: each chunk handles as many iterations as fit within a fixed element budget, keeping vectorization benefits without allocating gigabytes
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The bootstrap is a resampling technique that lets us estimate the sampling distribution of a statistic when we only have one sample. The core idea:
- Treat the sample as a population proxy. Our observed data is the best estimate we have of the true distribution.
- Resample with replacement. Draw n values randomly from the n observations, allowing duplicates. This simulates drawing a new sample from the population.
- Compute the statistic. Calculate the mean of each bootstrap sample.
- Repeat many times. With 10,000 resamples, we build an empirical distribution of the sample mean.
- Extract percentiles. The 95% confidence interval is the range from the 2.5th to 97.5th percentile of those 10,000 means.
Why it works: If we could repeatedly sample from the true population, the means would vary around the true mean with a certain spread. By resampling from our sample (with replacement to introduce variability), we approximate that spread. The percentile method captures the middle 95% of that distribution.
Critical details:
- Must sample with replacement. Without replacement, every resample is just a permutation—all means would be identical.
- Resample size must equal original size. The standard error of the mean scales as σ/√n. Changing the resample size would distort the interval width.
- Use percentiles, not standard deviation. The bootstrap distribution may be skewed, especially for small samples or heavy-tailed data like order values.
Performance Strategy
The naive approach loops 10,000 times in Python, calling np.random.choice each iteration. This is slow and throws away NumPy's vectorization.
Better: Generate all random indices at once in a matrix of shape (10000, n), then use fancy indexing to gather values and compute means with .mean(axis=1). Everything runs in compiled code.
Problem: A 10,000 × 100,000 matrix holds 1 billion elements—8 GB for float64 values plus 8 GB for int64 indices. This causes memory errors on typical machines.
Solution: Process in chunks. Decide on a maximum element budget (e.g., 5 million), compute how many resamples fit in one chunk, and iterate through chunks. Each chunk is fully vectorized, but total memory stays bounded. With only a handful of chunks, Python loop overhead is negligible.
Complexity
- Time: O(B · n) for generating and averaging B resamples of size n, plus O(B) for percentile extraction. With B = 10,000 and n = 10,000, that's ~100 million operations, typically under a second.
- Space: O(B + min(B·n, max_elements)). We always store the B means, plus one chunk at a time. The naive version would be O(B·n).
Edge Cases and Validation
- Empty input: Mean is undefined; raise an error.
- Non-finite values (NaN, infinity): These silently propagate through calculations. Detect and reject them upfront.
- All values identical: Every resample mean is the same. The CI collapses to a point—mathematically correct but signals insufficient data.
- Single observation: Same as above; return that value as both bounds.
- Skewed data: Order values are typically right-skewed with occasional large purchases. The percentile method handles this better than normal-theory intervals, but for extreme skew, bias-corrected methods (BCa) may be needed.
- Reproducibility: Accept a seed parameter so results are deterministic for testing and reporting.
Code
import numpy as np
def compute_bootstrap_ci(orders, n_resamples=10_000, confidence=0.95,
seed=None, max_elements=5_000_000):
"""
Compute bootstrap confidence interval for the mean.
Parameters
----------
orders : array-like
Observed order values
n_resamples : int
Number of bootstrap iterations
confidence : float
Confidence level (e.g., 0.95 for 95%)
seed : int, optional
Random seed for reproducibility
max_elements : int
Maximum elements per vectorized chunk (controls memory)
Returns
-------
(lower, upper) : tuple of floats
Confidence interval bounds
"""
# Convert and validate
data = np.asarray(orders, dtype=np.float64).ravel()
n = data.size
if n == 0:
raise ValueError("Input must contain at least one value")
if not np.all(np.isfinite(data)):
raise ValueError("All values must be finite (no NaN or inf)")
# Degenerate case: all identical or n=1
if n == 1 or np.ptp(data) == 0:
val = float(data[0])
return (val, val)
rng = np.random.default_rng(seed)
bootstrap_means = np.empty(n_resamples, dtype=np.float64)
# Determine chunk size: how many resamples fit in memory budget
chunk_size = max(1, max_elements // n)
# Process in chunks
for start_idx in range(0, n_resamples, chunk_size):
end_idx = min(start_idx + chunk_size, n_resamples)
batch_size = end_idx - start_idx
# Generate random indices: shape (batch_size, n)
# Each row is one bootstrap resample
indices = rng.integers(0, n, size=(batch_size, n))
# Gather values and compute means
resampled_data = data[indices]
bootstrap_means[start_idx:end_idx] = resampled_data.mean(axis=1)
# Extract percentiles
alpha = 1.0 - confidence
lower_percentile = 100 * alpha / 2
upper_percentile = 100 * (1 - alpha / 2)
lower, upper = np.percentile(bootstrap_means, [lower_percentile, upper_percentile])
return (float(lower), float(upper))
# Example usage
if __name__ == "__main__":
# Simulate realistic right-skewed order data
rng = np.random.default_rng(42)
order_data = rng.lognormal(mean=3.8, sigma=0.7, size=8_000)
lower, upper = compute_bootstrap_ci(order_data, seed=123)
# Compare to normal-theory interval as sanity check
sample_mean = order_data.mean()
std_error = order_data.std(ddof=1) / np.sqrt(order_data.size)
normal_lower = sample_mean - 1.96 * std_error
normal_upper = sample_mean + 1.96 * std_error
print(f"Sample mean: {sample_mean:.2f}")
print(f"Bootstrap 95% CI: ({lower:.2f}, {upper:.2f})")
print(f"Normal-theory CI: ({normal_lower:.2f}, {normal_upper:.2f})")
Common Mistakes
- Sampling without replacement or using a permutation—this gives zero variability.
- Using
mean ± 2·stdof the original data instead of percentiles of the bootstrap distribution. - Wrong resample size—using a fixed small number instead of n makes the interval too wide.
- Not vectorizing—10,000 Python loops are 100× slower than one NumPy operation.
- Ignoring memory—the naive vectorization runs out of memory on realistic data sizes.
- Using legacy
np.random.choice—it's slower and the global state isn't thread-safe; prefer the modern Generator API.
What Strong Candidates Mention
- The bootstrap approximates the sampling distribution by resampling from the empirical distribution
- Percentile intervals work better than normal approximations for skewed data
- The memory-performance tradeoff and why chunking solves it
- A sanity check: for moderate sample sizes and symmetric distributions, bootstrap and normal-theory intervals should be similar
- Awareness of more advanced methods (BCa) for heavily skewed or small samples
- Reproducibility via seeding for production use