note 68654 added to language.operators.arithmetic
| From: | UlfWostner at osu1 dot php dot net | Date: | Sat, 05 Aug 2006 07:13:14 +0000 |
| Subject: | note 68654 added to language.operators.arithmetic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-115564@lists.php.net to get a copy of this message | ||
# There are several natural ways to define the mod operator for integers.
# Requirement: If mod(k, m) = r, then k and r differ by a multiple of m.
# For m=7, think days-of-the-week. Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.
# There are several natural ways to define the mod operator for integers.
# Requirement: If mod(k, m) = r, then k and r differ by a multiple of m.
# For m=7, think days-of-the-week. Both mod(13, 7) = 6 and mod(13, 7) = -1
# satisfy the requirement. Six days from today, or one day ago, are the same DOW.
# Here are four mod operators:
# 1. mod_php.
# Same as the built-in PHP function, so mod_php($k,$m) == ($k % $m).
# A negative value might jolt a programmer using it for array index.
function mod_php($k, $m) {return $k % $m; }
# 2. Standard math definition.
# Nice. But, if for some reason m is negative, be prepared for negative values.
function mod_math($k, $m) { return ($k - $m * floor($k/$m)); }
# 3. Smallest absolute value.
# Sometimes convenient for large integers, making good use of the sign-bit.
# Also, for mere humans, "-2 months from May", might be easier than "10 months from
May".
function mod_min($k, $m) {
$r = mod_pos($k, $m);
if($r > abs($m)/2) $r -= abs($m);
return $r;
}
# 4. Smallest non-negative value.
# Maybe closest to the concept that mod is the remainder when dividing $k by $m.
function mod_pos($k, $m) { return ($k - abs($m) * floor($k/abs($m))); }
# This table compares the four functions.
k m mod_php mod_math mod_min mod_pos
18 7 4 4 -3 4
17 7 3 3 3 3
16 7 2 2 2 2
-16 7 -2 5 -2 5
-17 7 -3 4 -3 4
-18 7 -4 3 3 3
18 -7 4 -3 -3 4
17 -7 3 -4 3 3
16 -7 2 -5 2 2
-16 -7 -2 -2 -2 5
-17 -7 -3 -3 -3 4
-18 -7 -4 -4 3 3
----
Server IP: 216.194.113.175
Probable Submitter: 66.92.9.47
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/language.operators.arithmetic.php
Edit -- https://master.php.net/note/edit/68654
Del: integrated -- https://master.php.net/note/delete/68654/integrated
Del: useless -- https://master.php.net/note/delete/68654/useless
Del: bad code -- https://master.php.net/note/delete/68654/bad+code
Del: spam -- https://master.php.net/note/delete/68654/spam
Del: non-english -- https://master.php.net/note/delete/68654/non-english
Del: in docs -- https://master.php.net/note/delete/68654/in+docs
Del: other reasons-- https://master.php.net/note/delete/68654
Reject -- https://master.php.net/note/reject/68654
Search -- https://master.php.net/manage/user-notes.php