Monday, February 9, 2015

PHP standard deviation

PHP standard deviation

Sometimes your data is only a sample of the whole population. We can still estimate the Standard Deviation. But when you use the sample as an estimate of the whole population, the Standard Deviation formula changes to this:

The important change is "N-1" instead of "N" (which is called "Bessel's correction").

<?
function standard_deviation($aValues, $bSample = FALSE) {
  $dNum = $dNumOrig = count($aValues);
  $fSum = array_sum($aValues);
  $fMean = $fSum / $dNum;
  $fVariance = 0.0;

  foreach ($aValues as $i) {
    $fVariance += pow($i - $fMean, 2);
  }

  if ($bSample) {
    $dNum -= 1;
  }

  $fVariance = (double) sqrt($fVariance / $dNum);

  return array(
    'fUCL' => $fMean + $fVariance,  // Upper Control Limit
    'fLCL' => $fMean - $fVariance,  // Lower Control Limit
    'fMean' => $fMean,  // Average
    'fSum' => $fSum,
    'dNum' => $dNumOrig,
    'fVariance' => $fVariance,
  );
}

$arr = array(9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4);
$rs = standard_deviation($arr);

foreach ($arr as $val) {
  if ($val >= $rs['fLCL'] && $val <= $rs['fUCL']) {
    echo $val . ' inside of the range.' . "\n";
  }
  else {
    echo $val . ' outside of the range.' . "\n";
  }
}
?>

Reference:

http://www.mathsisfun.com/data/standard-deviation-formulas.html
http://www.mathsisfun.com/data/standard-deviation.html

No comments: