note 108174 deleted from ref.math by danbrown

From: Date: Wed, 04 Apr 2012 16:47:33 +0000
Subject: note 108174 deleted from ref.math by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-186969@lists.php.net to get a copy of this message
Note Submitter: milo at mdlwebsolutions dot com ---- @crescentfreshpot Regarding your median function, if you use $n % 2 == 0, you won't get what you think. Use is_int($n) instead. I forgot to sort my data. Not sure how to edit or remove a comment. <?php var_dump(2.5 % 2); //int(0) var_dump(4.5 % 2); //int(0) var_dump(5.5 % 2); //int(1) var_dump((5/2) % 2); //int(0) $n = 5 / 2;var_dump($n % 2); //int(0) $n = 4 / 2;var_dump($n % 2); //int(0) $n = 7 / 2;var_dump($n % 2); //int(1) $n = 9 / 2;var_dump($n % 2); //int(0) $n = 9 / 2;var_dump(is_int($n)); //bool(false) $n = 8 / 2;var_dump(is_int($n)); //bool(true) $n = 9 / 2;var_dump(floor($n)); //float(4) /** * @function median returns the median of an array of numeric values. * @param $data must have 1 or more values, all of which are numeric. * @variable $c_data is the number of items in the data set. * @variable $middle is the number of items divided by 2. This is * used to find the index of the middle value. * @return The median of the data set. * @example * On the complex example of an even number of values: * $data = array(0, 1, 2, 3); * $c_data = 4; * $middle = 2; * return 1.5; //($data[1] + $data[2]) / 2 * @example * On the complex example with an odd number of values: * $data = array(0, 1, 2, 3, 4); * $c_data = 5; * $middle = 2.5; * return 2; //$data[floor($middle)] * */ function median($data) { $c_data = count($data); $middle = $c_data / 2; sort($data); if ($c_data == 0) { return false; }//END IF if ($c_data < 2) { return $data[0]; } elseif (is_int($middle)) { return (($data[$middle - 1] + $data[$middle]) / 2); } else { return $data[floor($middle)]; }//END IF }//END FUNCTION

« previous php.notes (#186969) next »