Skip to content

Instantly share code, notes, and snippets.

@twfarland
Last active August 29, 2015 13:56
Show Gist options
  • Save twfarland/9079459 to your computer and use it in GitHub Desktop.
Save twfarland/9079459 to your computer and use it in GitHub Desktop.
Confidence score function mysql implementation (with negative score when downvotes > upvotes)
/* confidence score */
/* http://www.evanmiller.org/how-not-to-sort-by-average-rating.html */
drop function if exists confidence_score;
delimiter $$
create function confidence_score(upvotes int, downvotes int) returns double
begin
declare n int;
declare z double;
declare p double;
declare l double;
declare r double;
declare u double;
declare t_up int;
declare t_down int;
declare sign int;
/* reverse and make negative if more downvotes */
if downvotes > upvotes then
set t_up = downvotes;
set t_down = upvotes;
set upvotes = t_up;
set downvotes = t_down;
set sign = -1;
else
set sign = 1;
end if;
/* equation I don't understand */
set n = upvotes + downvotes;
set z = 1.96;
set p = upvotes / n;
set l = p + 1 / (2 * n) * z * z;
set r = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n));
set u = 1 + 1 / n * z * z;
if n = 0 then return 0;
else return sign * (l - r) / u;
end if;
end $$
delimiter ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment