note 26842 deleted from language.operators.arithmetic by sniper
| From: | sniper@php.net | Date: | Mon, 13 Oct 2003 00:08:25 +0000 |
| Subject: | note 26842 deleted from language.operators.arithmetic by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58386@lists.php.net to get a copy of this message | ||
Note Submitter: tld@tld.digitalcurse.com
----
Be aware of the % operator:
Modulus(A,B) is defined as the remainder of the division of A by B for A and B natural (positive
integers).
The extension to integer A (-1, -2, -3 and so on) can be done in two different ways: the first is by
congruence (A1 is congruent to A2 mod B if A1 + k*B = A2 for an integer k), the other is by absolute
value (for a negative A, A mod B = -((-A) mod B) ).
Values returned are in range [0, B) in the first case and (-B, B) in the second.
The first method validates (in PHP) [floor(A / B) * B + A % B == A], while the second validates
[sign(A)*floor(abs(A/B))* B + A % B == A]
BE AWARE! PHP implements the second method! This is not considered a bug by PHP coders, yet it can
cause a number of unexpected problems with mathematical axioms:
if ((-1 % 3) != (2 % 3)) { echo 'They are different'; }
WILL get to the echo, even if -1 = 2 mod 3; operations on time (no matter if 24h or 12h) might end
up with negative hours and so on.
To have the congruence method you can use this function:
function mod($a, $b) {
return ((($a % $b) + $b) % $b);
}
and then you'll have (mod(-1, 3) == mod(2, 3)), as expected. :)