Python
Wilson `Score`
Interval
Statistical Methods
Confidence Interval
Data Analysis

Wilson score interval in Python: formula and implementation

Codemia Knowledge Hub ·

The Wilson score interval is a confidence interval for a binomial proportion that stays reliable when the sample is small or the observed proportion is near 0 or 1, where the simple normal approximation breaks down. In Python you can implement it in a few lines with math.sqrt and statistics.NormalDist, no SciPy required.

Why not the naive normal interval

The interval most people learn first is:

  • p_hat ± z * sqrt(p_hat * (1 - p_hat) / n)

It can perform badly when:

  • n is small
  • the observed success rate is very low
  • the observed success rate is very high

The Wilson interval corrects this by shrinking the estimate toward the center in a principled way, which gives more realistic bounds.

The Wilson formula

Let:

  • x be the number of successes
  • n be the total number of trials
  • p_hat = x / n
  • z be the normal critical value, about 1.96 for a 95% interval

Then:

  • center = (p_hat + z^2 / (2n)) / (1 + z^2 / n)
  • margin = z / (1 + z^2 / n) * sqrt((p_hat * (1 - p_hat) + z^2 / (4n)) / n)
  • lower = center - margin
  • upper = center + margin

The bounds always stay within the valid probability range.

Implementation with the standard library

statistics.NormalDist provides the inverse CDF for the critical value, so z follows whatever confidence level you pass in:

python
1from math import sqrt
2from statistics import NormalDist
3
4
5def wilson_score_interval(successes, trials, confidence=0.95):
6    if trials <= 0:
7        raise ValueError("trials must be positive")
8    if not 0 <= successes <= trials:
9        raise ValueError("successes must be between 0 and trials")
10    if not 0 < confidence < 1:
11        raise ValueError("confidence must be between 0 and 1")
12
13    p_hat = successes / trials
14    alpha = 1.0 - confidence
15    z = NormalDist().inv_cdf(1.0 - alpha / 2.0)
16
17    denominator = 1.0 + (z ** 2) / trials
18    center = (p_hat + (z ** 2) / (2.0 * trials)) / denominator
19    margin = (z / denominator) * sqrt(
20        (p_hat * (1.0 - p_hat) + (z ** 2) / (4.0 * trials)) / trials
21    )
22
23    return center - margin, center + margin
24
25
26print(wilson_score_interval(42, 100))
27print(wilson_score_interval(1, 5))

The function validates its inputs: trials > 0 (with trials = 0 the formula is undefined), 0 <= successes <= trials, and 0 < confidence < 1. Avoid hardcoding z = 1.96 if the confidence level is meant to be configurable.

Reading the result

If an item gets 42 positive votes out of 100, the point estimate is 0.42, and the Wilson interval gives a range that expresses the uncertainty around it. With a much smaller sample, such as 1 success in 5 trials, Wilson is especially valuable because the naive approximation becomes unstable and misleading.

That is why Wilson score is popular in ranking systems, A/B testing summaries, and moderation or voting systems where sample sizes vary widely.

Using the lower bound as a ranking score

Many systems rank items by the lower bound of the interval, which rewards both a good success rate and enough evidence:

python
1
2def wilson_lower_bound(successes, trials, confidence=0.95):
3    lower, _ = wilson_score_interval(successes, trials, confidence)
4    return lower
5
6
7print(wilson_lower_bound(500, 1000))
8print(wilson_lower_bound(5, 10))

This stops tiny-sample items from ranking unrealistically high just because of a perfect early record.

Keep the function in proportion space ([0, 1]) and convert to percentages only when displaying results.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design