note 114473 added to function.stats-standard-deviation
| From: | levim@php.net | Date: | Mon, 24 Feb 2014 17:15:37 +0000 |
| Subject: | note 114473 added to function.stats-standard-deviation | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198631@lists.php.net to get a copy of this message | ||
Here's an implementation that adheres to the PECL source quite strictly. This is useful for
people who want to use it but don't have the extension, as well as for people who want to
understand what is going on.
<?php
if (!function_exists('stats_standard_deviation')) {
/**
* This user-land implementation follows the implementation quite strictly;
* it does not attempt to improve the code or algorithm in any way. It will
* raise a warning if you have fewer than 2 values in your array, just like
* the extension does (although as an E_USER_WARNING, not E_WARNING).
*
* @param array $a
* @param bool $sample [optional] Defaults to false
* @return float|bool The standard deviation or false on error.
*/
function stats_standard_deviation(array $a, $sample = false) {
$n = count($a);
if ($n === 0) {
trigger_error("The array has zero elements", E_USER_WARNING);
return false;
}
if ($sample && $n === 1) {
trigger_error("The array has only 1 element", E_USER_WARNING);
return false;
}
$mean = array_sum($a) / $n;
$carry = 0.0;
foreach ($a as $val) {
$d = ((double) $val) - $mean;
$carry += $d * $d;
};
if ($sample) {
--$n;
}
return sqrt($carry / $n);
}
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 128.187.97.24
----
Manual Page -- http://php.net/manual/en/function.stats-standard-deviation.php
Edit -- https://master.php.net/note/edit/114473
Del: integrated -- https://master.php.net/note/delete/114473/integrated
Del: useless -- https://master.php.net/note/delete/114473/useless
Del: bad code -- https://master.php.net/note/delete/114473/bad+code
Del: spam -- https://master.php.net/note/delete/114473/spam
Del: non-english -- https://master.php.net/note/delete/114473/non-english
Del: in docs -- https://master.php.net/note/delete/114473/in+docs
Del: other reasons-- https://master.php.net/note/delete/114473
Reject -- https://master.php.net/note/reject/114473
Search -- https://master.php.net/manage/user-notes.php