note 109234 modified in function.stats-standard-deviation by danbrown

From: Date: Mon, 16 Jul 2012 16:04:30 +0000
Subject: note 109234 modified in function.stats-standard-deviation by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189247@lists.php.net to get a copy of this message
Function to calculate square of value - mean

<?php
function sd_square($x, $mean) { return pow($x - $mean,2); }
?>

Function to calculate standard deviation (uses sd_square) 
<?php
function sd($array) {
 
// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );
}
?>

works better if you don't add +1 to the count

standard deviation of a constant must be 0 ( http://en.wikipedia.org/wiki/Standard_deviation )

different way :
<?php
class Tmath{
	public static function variance($data, $round = 2)
	{
		if( count($data) == 0 )
			return NULL;
		$total_ecart = 0;
		$moyenne = self::moyenne($data, 10*$round);
		if( $moyenne == 0)
			return 0;
		foreach( $data as $element)
		{
			$total_ecart += pow($element, 2);
		}
		return round($total_ecart/count($data) - pow($moyenne,2),$round);
	}
	public static function ecartType($data, $round = 2)
	{
		return round(sqrt(self::variance($data,10*$round)),2);
	}
	public static function moyenne($data, $round = 2)
	{
		if( count($data) == 0 )
			return NULL;
		return round(array_sum($data)/count($data),$round) ;
	}
}
?> --was-- // Function to calculate square of value - mean function sd_square($x, $mean) { return pow($x - $mean,2); } // Function to calculate standard deviation (uses sd_square) function sd($array) { // square root of sum of squares devided by N-1 return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) ); } works better if you don't add +1 to the count standard deviation of a constant must be 0 ( http://en.wikipedia.org/wiki/Standard_deviation ) different way : class Tmath{ public static function variance($data, $round = 2) { if( count($data) == 0 ) return NULL; $total_ecart = 0; $moyenne = self::moyenne($data, 10*$round); if( $moyenne == 0) return 0; foreach( $data as $element) { $total_ecart += pow($element, 2); } return round($total_ecart/count($data) - pow($moyenne,2),$round); } public static function ecartType($data, $round = 2) { return round(sqrt(self::variance($data,10*$round)),2); } public static function moyenne($data, $round = 2) { if( count($data) == 0 ) return NULL; return round(array_sum($data)/count($data),$round) ; } } http://php.net/manual/en/function.stats-standard-deviation.php

« previous php.notes (#189247) next »