note 108170 added to ref.math

From: Date: Wed, 04 Apr 2012 14:45:26 +0000
Subject: note 108170 added to ref.math
Groups: php.notes 
Request: Send a blank email to php-notes+get-186961@lists.php.net to get a copy of this message
@crescentfreshpot Regarding your median function, if you use $n % 2 == 0, you won't get what you think. Use is_int($n) instead. <?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; 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 ---- Server IP: 64.71.164.2 Probable Submitter: 71.43.135.46 ---- Manual Page -- http://www.php.net/manual/en/ref.math.php Edit -- https://master.php.net/note/edit/108170 Del: integrated -- https://master.php.net/note/delete/108170/integrated Del: useless -- https://master.php.net/note/delete/108170/useless Del: bad code -- https://master.php.net/note/delete/108170/bad+code Del: spam -- https://master.php.net/note/delete/108170/spam Del: non-english -- https://master.php.net/note/delete/108170/non-english Del: in docs -- https://master.php.net/note/delete/108170/in+docs Del: other reasons-- https://master.php.net/note/delete/108170 Reject -- https://master.php.net/note/reject/108170 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186961) next »