WRITE · TRACE · UNDERSTAND

Report uncertainty for a measured success rate

Implement wilson(successes,total,z=1.96) returning lower,upper.

Read lesson: Report uncertainty for a measured success rate →

Your experiment

Implement wilson(successes,total,z=1.96) returning lower,upper. Require integer 0<=successes<=total, total>0, and finite z>0. Clamp floating roundoff to [0,1].

Python runs in your browser. Your draft stays on this device.

What to look for

The z value determines the nominal confidence level through a normal approximation. Independence and representative sampling matter more than the number of decimals printed in the interval.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Report uncertainty for a measured success rate works

The idea

Five successes out of ten is an estimate, and an interval around it says where the true rate could plausibly lie. The textbook interval, the rate plus or minus z standard errors, fails on small samples and at the extremes: 0 successes out of 10 gets a width of zero.

The Wilson score interval asks instead which true rates would make the observed result unsurprising, using each candidate rate's own standard error. Solving that gives a centre pulled from p toward one half by z*z / (2*total) and a half-width with an extra z*z / (4*total*total) term under the square root. The interval stays inside 0 to 1 and keeps a sensible width even with no successes.

How it works

  1. Reject non-integer counts, successes outside 0 to total, a total below 1, and a z that is not finite and positive.
  2. Compute the observed rate p = successes / total and the shared denominator den = 1 + z*z/total.
  3. Compute center = (p + z*z/(2*total)) / den, which lies between p and one half.
  4. Compute half = z * sqrt(p*(1-p)/total + z*z/(4*total*total)) / den.
  5. Return center - half and center + half, clamped to 0.0 and 1.0 to remove floating-point overshoot.

What it costs

Time
O(1)
Space
O(1)

The interval is a closed formula with one square root, so it costs the same for ten trials or ten million.

Where it is used

  • Reddit ranks comments in its best sort by the lower bound of the Wilson score interval on upvotes.
  • statsmodels computes it with proportion_confint(count, nobs, method='wilson').
  • R's prop.test returns a Wilson score interval for a single proportion, with a continuity correction by default.

Watch out for

  • Using the simpler half-width z * sqrt(p*(1-p)/total), which collapses to zero when there are no successes or no failures.
  • Forgetting to divide both the centre and the half-width by 1 + z*z/total, which shifts and widens the interval.
  • Reading a 95 percent interval as a 95 percent chance for this one interval; the coverage describes the method over repeated samples.