php_joe Posted December 21, 2011 Share Posted December 21, 2011 Hello, I am trying to write a function that will calculate the standard deviation of values in an array. I did search past topics and used them to come up with this script: function standard_deviation($sample){ if(is_array($sample)){ $mean = array_sum($sample) / count($sample); foreach($sample as $key => $num) $devs[$key] = pow($num - $mean, 2); return sqrt(array_sum($devs) / count($devs)); } } It seems to work, but I get different values when I've checked it by using STDEV in OpenOffice, so I think I've made an error somewhere. Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/ Share on other sites More sharing options...
dzelenika Posted December 21, 2011 Share Posted December 21, 2011 try with: <?php function standard_deviation($sample){ if(is_array($sample)){ $mean = array_sum($sample) / count($sample); foreach($sample as $key => $num) $devs[$key] = pow($num - $mean, 2); return sqrt(array_sum($devs) / (count($devs) - 1)); } } ?> Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/#findComment-1300207 Share on other sites More sharing options...
Zane Posted December 21, 2011 Share Posted December 21, 2011 http://php.net/manual/en/function.stats-standard-deviation.php function standard_deviation($aValues, $bSample = false) { $fMean = array_sum($aValues) / count($aValues); $fVariance = 0.0; foreach ($aValues as $i) { $fVariance += pow($i - $fMean, 2); } $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) ); return (float) sqrt($fVariance); } Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/#findComment-1300209 Share on other sites More sharing options...
php_joe Posted December 21, 2011 Author Share Posted December 21, 2011 Thank you , However, that code returns the same value as the one I wrote. I guess the problem is with my spreadsheet's STDEV function. Joe Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/#findComment-1300212 Share on other sites More sharing options...
dzelenika Posted December 21, 2011 Share Posted December 21, 2011 is the difference notable or little? Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/#findComment-1300214 Share on other sites More sharing options...
php_joe Posted December 21, 2011 Author Share Posted December 21, 2011 Oh, sorry dzelenika, I didn't see your suggestion before. Your modification fixed the error, thanks! Link to comment https://forums.phpfreaks.com/topic/253594-standard-deviation/#findComment-1300240 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.