-
-
Save chrisneal/926a957364a48caee808528df8404522 to your computer and use it in GitHub Desktop.
[PHP] 5 Star Rating - Lower bound of Wilson score confidence interval for a Bernoulli parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
|-------------------------------------------------------------------------- | |
| 5 Star Rating | |
|-------------------------------------------------------------------------- | |
| | |
| Lower bound of Wilson score confidence interval for a Bernoulli parameter (0.9604) | |
| | |
| See: | |
| * http://www.evanmiller.org/how-not-to-sort-by-average-rating.html | |
| * https://gist.github.com/richardkundl/2950196 | |
| * https://onextrapixel.com/how-to-build-a-5-star-rating-system-with-wilson-interval-in-mysql/ | |
| | |
*/ | |
function score($positive, $negative) { | |
return ((($positive + 1.9208) / ($positive + $negative) - 1.96 * sqrt((($positive * $negative) / ($positive + $negative)) + 0.9604) / ($positive + $negative)) / (1 + 3.8416 / ($positive + $negative))); | |
} | |
function fiveStarRating($one, $two, $three, $four, $five) { | |
$positive = $two * 0.25 + $three * 0.5 + $four * 0.75 + $five; | |
$negative = $one + $two * 0.75 + $three * 0.5 + $four * 0.25; | |
return score($positive, $negative); | |
} | |
function fiveStarRatingAverage($avg, $total) | |
{ | |
$positive = ($avg * $total - $total) / 4; | |
$negative = $total - $positive; | |
return score($positive, $negative); | |
} | |
// Examples | |
echo fiveStarRating(10, 1, 2, 6, 90); // 0.80390178246001 | |
echo fiveStarRating(80, 1, 2, 6, 90); // 0.46188074417216 | |
echo fiveStarRating( 0, 1, 2, 6, 0 ); // 0.33136280289755 | |
echo fiveStarRating(10, 1, 2, 0, 2 ); // 0.079648861762752 | |
echo fiveStarRatingAverage(4.8000001907349, 10); // 0.65545605272928 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment