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

Bug with modulo operator and negative operands

Thread Next
From:
John Peacock
Date:
October 24, 2001 07:11
Subject:
Bug with modulo operator and negative operands
Message ID:
3BD6CBDE.D257BF4E@rowman.com
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:

http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2000-12/msg00499.html

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.

John

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About