Reputation: 8992
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
Reputation: 1
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
Reputation: 95131
You answer is correct :
The Basic Formula is :
Using Online Calculator
Therefore:
Upvotes: 2
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