Skip to content

Instantly share code, notes, and snippets.

@lnquy
Created March 30, 2021 09:08
Show Gist options
  • Save lnquy/2260d03011093641eb838b867d41ece2 to your computer and use it in GitHub Desktop.
Save lnquy/2260d03011093641eb838b867d41ece2 to your computer and use it in GitHub Desktop.
Lower bound of Wilson score confidence interval for a Bernoulli parameter: https://www.evanmiller.org/how-not-to-sort-by-average-rating.html
package main
import (
"fmt"
"math"
"gonum.org/v1/gonum/stat/distuv"
)
func main() {
// Use fixed value (quantile(95%) = 1.6448536269514715),
// if calculating normal distribution or importing gonum is too expensive for you.
z := distuv.UnitNormal.Quantile(0.95)
fmt.Println(z)
fmt.Println(score(600, 1000, z))
fmt.Println(score(5500, 10000, z))
}
// score returns a lower bound of Wilson score, best use when scoring/ranking.
// Make sure to read this first: https://www.evanmiller.org/how-not-to-sort-by-average-rating.html
//
// positive: Number of positive votes.
// total: Total number of votes.
// z: Inverse of the Gauss's normal distribution.
func score(positive, total, z float64) float64 {
if total == 0 {
return 0
}
phat := positive/total
return (phat + z*z/(2*total) - z * math.Sqrt((phat*(1-phat)+z*z/(4*total))/total))/(1+z*z/total)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment