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:
nis 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:
xbe the number of successesnbe the total number of trialsp_hat = x / nzbe the normal critical value, about1.96for a95%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:
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:
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.
Related reading
- Python in R - Error could not find a Python environment for /usr/bin/python
- Python Inverse of a Matrix
- Python k-means algorithm
- Python K-means fails to fit data when over 100 samples
- Python Implementations of Packing Algorithm
- Python import csv to list
- Python kernel dies on Jupyter Notebook with tensorflow 2
- Python memory usage of numpy arrays
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.