Uniform Random Sampling and Histogram Percentile Calculation
Statistics & ExperimentsModel answerLast updated
Generate uniformly distributed points in a square region and compute percentiles from binned frequency data using linear interpolation.
You need to solve two independent probability and statistics problems.
Problem 1: Random Point Generation
You have access to a function rand01() that produces a uniformly random floating-point number in [0, 1). Your task is to generate a uniformly random point (x, y) inside a square region with corners at (0, 0) and (S, S).
Write a function that returns such a point.
Problem 2: Percentile from Histogram
You are analyzing a dataset that has been aggregated into a histogram with M bins. You receive:
bin_edges: An array of M+1 boundary values [e_0, e_1, ..., e_M] where bin i covers the interval [e_i, e_{i+1})bin_counts: An array of M integers [c_0, c_1, ..., c_{M-1}] where c_i is how many data points fell into bin ip: A percentile value between 0 and 1 (for example, 0.75 represents the 75th percentile)
Implement a function that estimates the p-th percentile value by assuming uniform distribution of points within each bin and using linear interpolation.
Example Walkthrough
Given:
bin_edges= [0, 10, 20, 30]bin_counts= [100, 200, 100]p= 0.50
Solution steps:
- Total observations = 100 + 200 + 100 = 400
- Target position = 0.50 × 400 = 200
- Cumulative counts: 100 (after bin 0), 300 (after bin 1)
- Position 200 lies in bin 1, which spans [10, 20)
- Within bin 1: we need the 100th out of 200 values (since 100 came before)
- Interpolated value = 10 + (100/200) × (20 - 10) = 15
Assumptions and Constraints
- All bin counts are non-negative integers
- Bin edges are in strictly increasing order
- Percentile p is in the range [0, 1]
- Assume data is uniformly distributed within each bin
Hints
Hint 1
For the square sampling: each coordinate can be generated independently by scaling the [0,1) random value to [0,S)
Hint 2
For percentiles: first find which bin contains your target rank by accumulating counts from left to right
Hint 3
Use the formula: value = left_edge + (fraction_through_bin) × bin_width, where fraction depends on how many values you need from that bin
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem 1: Uniform Random Point in Square
Approach
The key insight is that uniform random variables can be independently scaled. If u is uniform on [0, 1), then S × u is uniform on [0, S).
To generate a point (x, y):
- Call
rand01()to get the first random value, multiply by S to get x - Call
rand01()independently to get a second random value, multiply by S to get y - Return (x, y)
This works because the joint probability density is the product of the individual densities: f(x,y) = (1/S) × (1/S) = 1/S², which is constant across the entire square—the definition of uniform distribution over an area.
Time Complexity: O(1)
Space Complexity: O(1)
Problem 2: Percentile Estimation from Histogram
Approach
The strategy is to locate which bin contains the target percentile, then interpolate linearly within that bin.
Algorithm:
- Calculate total count N = sum of all bin_counts
- Calculate target rank t = p × N (the position we're looking for)
- Iterate through bins while maintaining a cumulative count
- When cumulative_count + current_bin_count ≥ t, we've found the right bin
- Calculate how far into this bin our target lies
- Use linear interpolation:
value = left_edge + (offset / bin_count) × (right_edge - left_edge)
Why Linear Interpolation?
We assume data points are evenly spread within each bin. If a bin has 200 values spanning [10, 20), we model them as occurring at positions 10.00, 10.05, 10.10, ..., 19.95. The cumulative distribution function (CDF) rises linearly from the left edge to the right edge within each bin.
Time Complexity: O(M) where M is the number of bins (single pass)
Space Complexity: O(1) auxiliary space
Implementation
from typing import Callable, List, Tuple
def sample_square(S: float, rand01: Callable[[], float]) -> Tuple[float, float]:
"""Generate a uniform random point in the square [0,S) × [0,S)."""
if S <= 0:
raise ValueError("Side length must be positive")
x = S * rand01()
y = S * rand01()
return (x, y)
def estimate_percentile(bin_edges: List[float],
bin_counts: List[int],
p: float) -> float:
"""
Estimate the p-th percentile from histogram data using linear interpolation.
Args:
bin_edges: M+1 boundary values defining M bins
bin_counts: M counts, one per bin
p: percentile in [0, 1]
Returns:
Estimated percentile value
"""
M = len(bin_counts)
# Validation
if len(bin_edges) != M + 1:
raise ValueError("bin_edges must have exactly one more element than bin_counts")
if not (0 <= p <= 1):
raise ValueError("Percentile p must be in [0, 1]")
total_count = sum(bin_counts)
if total_count == 0:
raise ValueError("Cannot compute percentile of empty dataset")
target_rank = p * total_count
cumulative = 0
last_valid_edge = -1
for i in range(M):
count = bin_counts[i]
if count > 0:
last_valid_edge = i + 1
if cumulative + count >= target_rank:
# Target is in this bin
left = bin_edges[i]
right = bin_edges[i + 1]
offset_in_bin = target_rank - cumulative
fraction = offset_in_bin / count
return left + fraction * (right - left)
cumulative += count
# Edge case: target equals total (p=1.0) or floating point rounding
return bin_edges[last_valid_edge]
Example Verification
For bin_edges = [0, 10, 20, 30], bin_counts = [100, 200, 100], p = 0.50:
- Total = 400, target = 200
- After bin 0: cumulative = 100
- After adding bin 1: cumulative would be 300, which ≥ 200, so target is in bin 1
- Bin 1 spans [10, 20) with 200 values
- We need position 200, and 100 came before this bin
- Offset within bin = 200 - 100 = 100
- Fraction = 100/200 = 0.5
- Result = 10 + 0.5 × 10 = 15.0
Common Mistakes
- Not scaling both coordinates independently in the square sampling problem
- Using
r = R × rand01()for circle sampling (radius should be R × √rand01()) - Forgetting that bin_edges has M+1 elements for M bins
- Not handling empty bins (bins with count = 0 should be skipped)
- Off-by-one errors in cumulative counting
- Division by zero when interpolating in an empty bin
Edge Cases to Handle
- p = 0: Returns the left edge of the first non-empty bin
- p = 1: Returns the right edge of the last non-empty bin
- Empty bins: Skip them; never interpolate through zero-count bins
- All bins empty: Should raise an error
- Single observation: Any percentile returns that value's bin position
- Target on bin boundary: The >= comparison ensures consistent behavior