I'm trying to perform modulus arithmetic on negative numbers, and PHP insists on returning the wrong answer.
According to my Hewlett-Packard calculator and various Web documents, (-1 % 7) is 6, but PHP returns -1 (the sign is correct per the docs). Thus, abs(-1 % 7) returns 1, not 6.
The ONLY way I can get PHP to return the correct modulus result is to add 7 before taking the modulus, as:
$x = -1;
$result = abs($x + 7) % 7);
Does anyone know why PHP won't return the right answer on negative numbers?
Mike
Is modulus broken on negative numbers?
Moderator: General Moderators
Re: Is modulus broken on negative numbers?
PHP defines A % B as the remainder from the division A / B. According to that definition PHP is doing the right thing.
Modulus with negative numbers varies. "Math" defines it one way, PHP (and many other computing languages) define it the other way.
In either case,
And your fix is incorrect. What about -8 % 7?
Modulus with negative numbers varies. "Math" defines it one way, PHP (and many other computing languages) define it the other way.
In either case,
Code: Select all
$A % $B == floor($A / $B) * $A + ($A % $B)Code: Select all
$amodb = $A % $B;
if ($amodb < 0) $amodb += $B;Re: Is modulus broken on negative numbers?
Good point; thanks. My fix was fine for my specific application, which involves finding the day-of-month for the nth "xxxday" (e.g., third Thursday), so the number is always 0..6 or o..-6 (difference between first day-of-month (0..6) and first desired day-of-week (0..6).tasairis wrote: And your fix is incorrect. What about -8 % 7?Code: Select all
$amodb = $A % $B; if ($amodb < 0) $amodb += $B;
Nevertheless, I changed my code to your suggestion, in case I copy it in the future for a more general application.
Mike