Zend - The PHP Company




Math

Add Code


Standard Deviation  

Type: code fragment
Added by: bstrain
Entered: 02/07/2002
Last modified: 07/12/2001
Rating: - (fewer than 3 votes)
Views: 8631
Calculates the Standard Deviation of an array of numerical values.


<?php
#This function returns the standard deviation of an array
#of numerical values where $std is the array name.

function standard_deviation($std
    {
    
$total;
    while(list(
$key,$val) = each($std))
        {
        
$total += $val;
        }
    
reset($std);
    
$mean $total/count($std);
        
    while(list(
$key,$val) = each($std))
        { 
        
$sum += pow(($val-$mean),2);
        } 
    
$var sqrt($sum/(count($std)-1));
    return 
$var
    }
?>


Usage Example


function standard_deviation($std) 
     {
     $total;
     while(list($key,$val)=each $std))
          {
          $total += $val;
          }
     reset($std);
     $mean = $total/count($std);
     while(list($key,$val) = each($std))
          {
          $sum += pow(($val-$mean),2);
          }
     $var = sqrt($sum/(count($std)-1));
     return $var; 
     }
$values="1,2,2,4,4,4,5,5,6,6,3,3,4,8,7";
$std = explode(",",$values);

print standard_deviation($std);


Rate This Script





Search



This Category All Categories