Is modulus broken on negative numbers?
Posted: Sun May 10, 2009 5:50 pm
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
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