Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save anwarmuhamat/19f07b8aea4c5b966f84 to your computer and use it in GitHub Desktop.

Select an option

Save anwarmuhamat/19f07b8aea4c5b966f84 to your computer and use it in GitHub Desktop.
<?php
namespace ScoreCalculator;
/**
* Calculate a score based on a Wilson Confidence Interval
*
* Based on concepts discussed at @link http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
*/
class WilsonConfidenceIntervalCalculator implements ScoringAlgorithmInterface
{
/**
* Computed value for confidence (z)
*
* These values were computed using Ruby's Statistics2.pnormaldist function
* 1.959964 = 95.0% confidence
* 2.241403 = 97.5% confidence
*/
const CONFIDENCE = 2.241403;
/** {@inheritDoc} */
public function calculate($positiveVotes, $totalVotes)
{
return $totalVotes ? $this->average($positiveVotes, $totalVotes) : 0;
}
private function average($positiveVotes, $totalVotes)
{
$avg = 1.0 * $positiveVotes / $totalVotes;
$numerator = $this->calculationNumerator($totalVotes, self::CONFIDENCE, $avg);
$denominator = $this->calculationDenominator($totalVotes, self::CONFIDENCE);
return $numerator / $denominator;
}
private function calculationDenominator($total, $z)
{
return 1 + $z * $z / $total;
}
private function calculationNumerator($total, $z, $avg)
{
return $avg + $z * $z / (2 * $total) - $z * sqrt(($avg * (1 - $avg) + $z * $z / (4 * $total)) / $total);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment