Skip to content

Instantly share code, notes, and snippets.

@amix
Created March 19, 2016 11:10
Show Gist options
  • Save amix/8d14ff0a920d5c15738a to your computer and use it in GitHub Desktop.
Save amix/8d14ff0a920d5c15738a to your computer and use it in GitHub Desktop.
The confidence sort in pure Python (from Reddit's codebase)
# Rewritten code from /r2/r2/lib/db/_sorts.pyx
from math import sqrt
def _confidence(ups, downs):
n = ups + downs
if n == 0:
return 0
z = 1.281551565545
p = float(ups) / n
left = p + 1/(2*n)*z*z
right = z*sqrt(p*(1-p)/n + z*z/(4*n*n))
under = 1+1/n*z*z
return (left - right) / under
def confidence(ups, downs):
if ups + downs == 0:
return 0
else:
return _confidence(ups, downs)
@phoglenix
Copy link

In python2 x/y is integer division, so line #13 and #15 will be incorrect.
Easily fixed by moving the z*z to the left of the division.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment