| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
The code below rounds a value up to a nearest multiple, away from zero. The multiple does not have to be a integer. So you could round, say, to the nearest 25.4, allowing you to round measurements in mm to the nearest inch longer.
<?php
// $x is the variable
// $c is the base multiple to round to, away from zero
$result = ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
?>
I originally developed this as an example of write-only code: to make the point that being cleverly terse might save clock ticks but wastes more in programmer time generating un-maintainable code.
The inline code above nests one conditional statement inside another. The value of y changes twice within the same line (three times, if you count the pre-increment). The value of each assignment is used to determine branching within the conditional statement.
How it works can more easily be seen from the expansion below:
<?php
function myCeilingLong($x,$c)
{
// $x is variable
// $c is ceiling multiple
$a = $x/$c ;
$b = (int)$a ;
if ($a == $b)
return $x ; // x is already a multiple of c;
else
{
if ($x>=0)
return ($b+1)*$c ; // return ((int)(x/c)+1 ) * c
else
return ($b-1)*$c ; // return ((int)(x/c)-1 ) * c
}
}
?>
<?php
function myCeilingShort($x,$c)
{
return ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
}
?>
Comparing the versions for speed: the in-line version is about three times faster than myCeilingLong() - but this is almost entirely down to function call overhead.
Putting the in-line code inside the function: the difference in execution speed between myCeilingLong() and myCeilingShort() is around 1.5%.
ceil() is still around 25% faster than the in-line statement so if you are a speed hound your efforts might be better devoted to compiling your own library ...
----
Server IP: 92.48.74.199
Probable Submitter: 195.112.2.119
----
Manual Page -- http://www.php.net/manual/en/function.ceil.php
Edit -- https://master.php.net/note/edit/102796
Del: integrated -- https://master.php.net/note/delete/102796/integrated
Del: useless -- https://master.php.net/note/delete/102796/useless
Del: bad code -- https://master.php.net/note/delete/102796/bad+code
Del: spam -- https://master.php.net/note/delete/102796/spam
Del: non-english -- https://master.php.net/note/delete/102796/non-english
Del: in docs -- https://master.php.net/note/delete/102796/in+docs
Del: other reasons-- https://master.php.net/note/delete/102796
Reject -- https://master.php.net/note/reject/102796
Search -- https://master.php.net/manage/user-notes.php