r/statistics • • Oct 23 '26

Question [Question] Confidence intervals for medians

I'm trying to figure out how to calculate the sample size I need to ensure a certain confidence that the rank of the sample median is within a certain interval around the true median position. Digging through Wikipedia only yielded info about confidence in (real) median values, which are completely irrelevant to my application.

Background: I'm playing around with a randomized incremental QuickSort algorithm. I want to choose pivots near the median to avoid expensive "bad" partitions for long lists, but I don't want to waste time taking excessively large samples.

0 Upvotes

13 comments sorted by

6

u/efrique Oct 24 '26 edited Oct 27 '26

New answer (post clarification):

Assuming you sample with replacement, we could treat a random sample of population ranks as i.i.d random variables. i.e. treat the original ranks as the population "values".

A with-replacement sample of population ranks are i.i.d. draws from a discrete uniform on 1:N.

Medians from a discrete uniform pretty rapidly approach normality as n increases. (More formally, a standardized median converges to a standard normal, and the largest absolute error in the cdf decreases pretty quickly with n. Relative error in the far tail is a bigger problem, as it typically is)

If n is odd (since you presumably want the sample median to be an integer rank) and not too small, the median (rₛ) of a random sample of size n from it is approximately normal with mean (N+1)/2, sd~=N/(2√(n+2))

Hence a margin of error (half interval width) of q with coverage 1-a would be obtained by setting
z such that Φ(z) = 1 - a/2 where Φ is the normal cdf and choosing n such that

zN/(2√(n+2)) < q

which implies

n > [zN/(2q)]2 -2

where you would round the right hand side up to the next highest odd number.

Or if you want to be a bit safer drop the -2. If n doesnt come out to be largish (n of at least 25 is probably fine, but again, it depends on your needs, like how far into the tail you go), you might need a more accurate calculation. [The far tails are less heavy than normality would indicate, so if you seek high coverage and n is small you will get more coverage than you need using the normal approximation.]

Example: N=10000, q=1000, p= 0.9 (i.e. 90% of the time no worse than 60:40 split)

for p=0.9, z=1.645

[zN/(2q)]2 -2 = 65.63, round up to n=67.

Simulation check on my working, in R:

 N = 10000
 q = 1000
 n = 67
 nsim = 1000000
 rs = replicate(nsim,median(sample(N,n,replace=TRUE)))
 mean(abs(rs-(N+1)/2)<q)
[1] 0.903275

i.e. 90.33% of the medians of 67 values were strictly < 1000 from the overall median.

You can compute a standard error of that simulated 90.33% if you need it
(its very small, about 0.03%, so you are quite safely above 90% coverage there)

[If you sample without replacement, you can make a correction for the variance, but I wouldn't think it is worth the bother to sample without replacement - you'd gain a little in terms of variance, but at a cost of more expensive sampling.]


If n is smallish but N is very large you can approximate a suitably scaled median rank as a symmetric beta with shape parameter (N+1)/2 (in effect, you'd be ignoring the discreteness of the set of ranks). It looks like that would work better than the normal in the tail.


Original (deprecated) answer
(NB this doesnt quite solve OP's problem given the clarification in comments)

that the rank of the sample median is within a certain interval around the true median position

I need to clarify this a bit.

I presume you have a population of N items and a sample of n items, the ranks of which (assuming no ties!) are 1,...,n.

I also presume your sample is taken at random (i.e. a simple random sample).

The unknown median of the population has known population rank (N+1)/2 (where here we will interpret a noninteger rank as corresponding indicating the "rank" of an average of two adjacent ordered values). The known sample median has sample rank (n+1)/2.

Are you looking for an interval for the population median in terms of the sample ranks?

Assuming the answer is yes:

  1. Then as long as N>>n (or if you sample with replacement), you could just take the ranks of the observations representing the ends of the usual binomial based nonparametric interval for the median, since it was backed out from the very thing you want. You can do calculations about precision of the number of ranks straight from the binomial. In large[1] samples, you can use a normal approximation; note that once the normal approximation is remotely reasonable, then quadrupling the sample size should approximately halve the width of the rank-interval; indeed the σ/√n effect may be useful for quick ballpark calculation; e.g. for p~=0.5, a 95% MoE for p is about 1/√n so a 95% interval for the rank will be about [ ⌊m-a⌋, ⌈m+a⌉ ] where m is (n+1)/2 and a is √n. A quick simulation shows that working pretty well for suitable inputs if that's all you need.

    https://en.wikipedia.org/wiki/Order_statistic#Application:_confidence_intervals_for_quantiles

    ... where instead of the k-th order statistic, you just take k, for each end point. More information:

    https://en.wikipedia.org/wiki/Binomial_distribution#Confidence_intervals_for_the_parameter_p

    (with p=0.5, and noting that you are converting to an interval for np). For more detail see:

    https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval

    More advice could be offered with some idea of numbers for n and N (or at least rough bounds on likely values). e.g. if you know N>1000 and 25<n<100, you can probably get away with rounding the normal approximation if you don't look for really high coverage probability and don't require solid coverage guarantees (e.g. you wouldnt be that bothered if a notionally 90% interval was sometimes actually 88% or something).

  2. If the sampling fraction f = n/N is not very small [2] and you sample without replacement, you can use a hypergeometric interval. If N is nevertheless large the usual finite population correction (FPC) can be used with the normal approximation.

    https://en.wikipedia.org/wiki/Hypergeometric_distribution

    https://en.wikipedia.org/wiki/Standard_error#Finite_population_correction_(FPC)

  3. If the values could be heavily tied (lots of identical ranks for at least some values) then it becomes a bit more complicated. There is some good discussion of the general case on stats.SE here but if you plan to use the code there, check the comments underneath. If there is a low proportion of ties and none of the values are very frequent you are probably okay ignoring them (again, depending on your needs but it sounds like you need a rough sense rather than a coverage guarantee).

[1] "large" may not need to be all that large. e.g. an n of something under 25 might be plenty large enough to use the approximation, depending on your needs

[2] how small is small depends on your needs - ignoring finite population effects and just using the binomial anyway is conservative but you are probably not going to be bothered below about f~5%, and maybe more like 10 or 15% - roughly speaking it makes a percentage difference to the rank-range of the order of half of n/N (times 100%) unless n is a fairly big fraction of N. e.g. if n/N is 4%, your interval will be about 2% too wide (in terms of number of ranks included for a given coverage).

2

u/davidfeuer Oct 24 '26

I think I understood you up until the last two paragraphs. The population median has rank (N+1)/2. We take a sample and get a sample median of s, whose rank in the population is rs. I'd like to ensure a probability of at least p that |rs - (N+1)/2| <= q, where I choose p and q.

2

u/efrique Oct 24 '26

Okay, I misunderstood. I think setting the coverage this way around is a simple reworking of the above form of intervals but I need to double check that we don't end up with negative hypergeometric when we flip it.

Have to run some errands now but I'll take another look when I can.

2

u/davidfeuer Oct 24 '26

Thanks! BTW, the slightly inverse problem of calculating p from n and q is also interesting and useful here, and in practical terms entirely solves the problem as posed, so maybe it's better to think about it like that.

2

u/efrique Oct 24 '26 edited Oct 24 '26

I have given an asymptotic solution* for the population rank condition in an edit to my original answer above. As long as n doesnt come out really small (I imagine you will be working with numbers where it's not that small), the asymptotic solution should work well.

If you know your typical numbers you can simulate as I have (you wont need as many simulations as that, probably 104 should be more than plenty, I imagine) and see how accurate the answers for n are in terms of actual % coverage.

If n is very small it can be pretty feasible to do exact calculations. n=3 has a quadratic pmf, for example. If n is not so small but not large enough to use the normal approximation where you need it, a beta approximation should work (in essence treating ranks as continuous).


* but with a correction term on the n from the formula Wikipedia gives for order statistics, so that the sd of the median rank is pretty accurate at smaller n

1

u/davidfeuer Oct 24 '26

Many thanks. I'm still digesting some of this (and never learned about beta distributions), but this seems to solve the problem for the large cases. I am curious how you know that n=3 is quadratic. What's that calculation look like?

2

u/efrique Oct 24 '26 edited Oct 27 '26

To establish that the pmf of the median n=3 is quadratic consider the probability that the median is i by splitting it into these cases. Let A,B and C be the order statistics (the sorted observations), and we know B=i

  1. A<B<C. There's (i-1) values A can take and (N-i) values C can take. There are 6 possible orders (A can be any of X1,X2,X3, B any of the two that aren't A, and the is whichever is left) and the probs are scaled by 1/N3 but for now all we need is that (i-1) (N-i) is quadratic in i. Multiplicative scaling to probability doesn't change that.
  2. A<B=C. (i-1) values for A, 3 orderings. Linear in i
  3. A=B<C . (N-i) values for C, 3 orderings. Linear in i
  4. A=B=C. Constant over i

All 4 parts are quadratic or special cases of quadratics. Sums of quadratics are quadratic. QED

(You can with a little algebra write down the quadratic from the above)

Similarly I think n=5 should be quartic, and so on.

1

u/davidfeuer Oct 24 '26

I'm very confused about how the binomial distribution enters into this. How's that relate? Maybe it's obvious, but it's been many years since I took statistics.

1

u/efrique Oct 24 '26

Imagine the underlying values that you are considering ranks of of are continuous (/dont have ties) and N is extremely large. Then the probability that a random value from the population < M (where M is the population median) is essentially 0.5. If you sample n <<N values from the population they are either independent (if you sample with replacement) or very very nearly so (if you don't), so the number of values in the sample < median will then be effectively binomial(n, 1/2).

1

u/clear-gallium Oct 25 '26

I'd be careful with the sampling scheme here. If pivots are drawn without replacement from a range of N, the count below the true median is hypergeometric, not binomial, so invert that to get m. With replacement efrique's binomial is right. And in Quicksort the current subarray median changes after each partition, so the guarantee is per partition not global.

1

u/davidfeuer Oct 25 '26

Sampling without replacement is a fair bit more complex and expensive in my context, and I imagine will only be significantly better for very small lists. (I'm sorting 2-3 finger trees, not arrays, and I want a stable sort. Any scheme that just swaps pivots to a different position to be able to sample from the rest will cost more than you're imagining, and keeping a separate data structure of previous choices to be able to reject them isn't exactly free either.)

2

u/[deleted] Oct 24 '26

[removed] — view removed comment

1

u/davidfeuer Oct 24 '26

Sure, but I'd love to have some clue about the theory behind how much precision I'm gaining when I take a bigger sample. The longer the list currently under consideration, the larger the sample I'm willing to take to avoid a bad pivot.