Skip to content

Instantly share code, notes, and snippets.

@apeckham
Created March 7, 2012 18:40
Show Gist options
  • Save apeckham/1995032 to your computer and use it in GitHub Desktop.
Save apeckham/1995032 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION ci_lower_bound(integer, integer) RETURNS numeric LANGUAGE plpgsql IMMUTABLE
AS $$
DECLARE
up_votes ALIAS FOR $1;
total_votes ALIAS FOR $2;
z numeric;
p_hat numeric;
BEGIN
IF total_votes <= 0 OR up_votes < 0 OR up_votes > total_votes THEN
RETURN 0;
END IF;
z := 1.96;
p_hat := 1.0 * up_votes / total_votes;
RETURN (p_hat + z * z / (2 * total_votes) - z * sqrt((p_hat * (1 - p_hat) + z * z / (4 * total_votes)) / total_votes)) / (1 + z * z / total_votes);
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment