pillarOfLight
pillarOfLight

Reputation: 8992

my custom PHP stdev function VS mysql's STDDEV_POP

So I have this code:

$arr = array(
  1,2,3,4,5,6
);
$num = count($arr);
$sum = array_sum($arr);
$average = $sum/$num;
foreach($arr as $val) {
  $sum += pow(($val - $average), 2);
}
$stdev = sqrt($sum / ($num - 1));

versus

SELECT STDDEV_POP(something) FROM table;

whereby table is

Something
'1'
'2'
'3'
'4'
'5'
'6'

And yet $stdev returns

2.7748873851023

whereas the select returns 1.707825127659933

What's wrong with my stdev code?

Upvotes: 0

Views: 424

Answers (3)

i use this function, it great to my work

function find_stdev($arr){
    $a=0;
    foreach($arr as $val) {
      $a += (pow($val,2));
    }
    $n = count($arr);
    $sum = array_sum($arr);
    $a = $a*$n;
    $b = pow($sum,2);
    $c = ($a-$b)/($n*($n-1));

    $stdev = sqrt($c);

    return $stdev;
}

Upvotes: 0

Baba
Baba

Reputation: 95131

You answer is correct :

The Basic Formula is :

enter image description here

Using Online Calculator

enter image description here

Therefore:

enter image description here

Upvotes: 2

Jack M.
Jack M.

Reputation: 1170

This gave me your 1.70

$arr = array(
  1,2,3,4,5,6
);
$num = count($arr);
$sum2 = 0;
$sum = array_sum($arr);
$average = $sum/$num;
foreach($arr as $val) {
  $sum2 += pow(($val - $average), 2);
}
$stdev = sqrt($sum2 / ($num));
echo $stdev;exit;

Upvotes: 1

Related Questions