note 68654 deleted from language.operators.arithmetic by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 15:05:00 +0000 |
| Subject: | note 68654 deleted from language.operators.arithmetic by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189805@lists.php.net to get a copy of this message | ||
Note Submitter: Ulf Wostner
----
# 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