develooper Front page | perl.perl5.porters | Postings from October 2001

Bug with modulo operator and negative operands

Thread Next
John Peacock
October 24, 2001 07:11
Bug with modulo operator and negative operands
Message ID:
With the following trivial code Tels and I have rediscovered a bug
with the code underlying the modulo operator in Perl as far back
as 5.005_02 and platforms as varied as Linux, CygWin, and AIX.

$numerator = -11;
$denominator = 2;
$modulo = $numerator % $denominator;
use integer;
$numerator = -11;
$denominator = 2;
$modulo = $numerator % $denominator;

which prints out

-11 % 2 = 1
-11 % 2 = -1

If I use Devel::Peek::Dump(), I can see that all terms are IV's
except the first $modulo when 'use integer;' is NOT in effect, where 
it is a UV (presumably explaining the lack of sign).  If I do the 
comparable c code:

#include <stdio.h>
int main() {
        int numerator, denominator, modulo;
        numerator = -11;
        denominator = 2;
        modulo = numerator % denominator;
        printf(" %d %% %d => %d\n",numerator, denominator, modulo);

I indeed get 

	-11 % 2 = -1

which at least agrees with the information I can glean from the ANSI C
rationalization regarding the div() function.  I do see that K&R
2nd edition (ancient I know, but what I happen to have on the shelf) 
mentions that the / and % operators are machine dependent for negative 
operands.  Argh.

Regardless of the validity of the argument that the modulo should
be -1 in this case, the 'use integer;' should have no effect on
the answer on any single machine.

I did a search on the archive and found that there has been
some extensive discussion about what the right thing to do is.
However, the patch mentioned here to clean up the 64-bit arithmetic:

which went in as 8120/8119 specifically excluded divide and
modulo, and at first glance I don't see any other patch that
followed up to cover those cases.

Comments, arguments, etc. gladly accepted.  Hearing none, I will
endeavor to produce a patch.


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About