Page 1 of 1

Is modulus broken on negative numbers?

Posted: Sun May 10, 2009 5:50 pm
by ,ikedodd
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

Re: Is modulus broken on negative numbers?

Posted: Sun May 10, 2009 8:23 pm
by requinix
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,

Code: Select all

$A % $B  ==  floor($A / $B) * $A  +  ($A % $B)
And your fix is incorrect. What about -8 % 7?

Code: Select all

$amodb = $A % $B;
if ($amodb < 0) $amodb += $B;

Re: Is modulus broken on negative numbers?

Posted: Mon May 11, 2009 9:17 pm
by ,ikedodd
tasairis wrote: And your fix is incorrect. What about -8 % 7?

Code: Select all

$amodb = $A % $B;
if ($amodb < 0) $amodb += $B;
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).

Nevertheless, I changed my code to your suggestion, in case I copy it in the future for a more general application.

Mike