Skip to content

Instantly share code, notes, and snippets.

@kfwebdev
Forked from julienbourdeau/wilson.php
Created September 10, 2019 08:13
Show Gist options
  • Save kfwebdev/81a35e0cdc70d91371c686056f9c5f86 to your computer and use it in GitHub Desktop.
Save kfwebdev/81a35e0cdc70d91371c686056f9c5f86 to your computer and use it in GitHub Desktop.
[PHP] 5 Star Rating - Lower bound of Wilson score confidence interval for a Bernoulli parameter
<?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