[Python-bugs-list] Divide overflow (follow-on to bug #88) (PR#169)

sjmachin@lexicon.net sjmachin@lexicon.net
Thu, 6 Jan 2000 07:53:55 -0500 (EST)


The Tim emitted:
> [John Machin]
> > Pedantry would say that BIGNEG % -1 should *not* cause an
> > exception, but return a result of zero.
> 
> The Lang Ref (section 5.6, Binary arithmetic operations) guarantees that
> 
>     x == (x/y)*y + (x%y)
> and
>     divmod(x, y) == x/y, x%y
> 
> for integer x and y, so if you can compute any one of {divmod(x,y), x/y,
> x%y} without exception, you have every right to insist all three be
> computable without exception, and to insist that the results satisfy
> these identities.  So the *truly* pedantic <wink> answer is the one
> that's implemented.

It says the integer division and modulo operators are connected by the 
identity x == (x/y)*y + (x%y) etc etc. I don't see how you can construe 
that as a guarantee, nor how you infer the right to insist that all 
three be computable if one is.

However O great Tim I'll leave the field to you as the archdefiner of 
pedantry ;-)

> 
> > ... I'm just suggesting that this be added to the documentation
> > in the reference manual.
> 
> Just noting that the docs currently define no case of OverflowError, let
> alone this end case.

*snort* see Lang Ref section 3.2:
<quote>
Plain integers
These represent numbers in the range -2147483648 through 2147483647. 
(The range may be larger on machines with a larger natural word size, 
but not smaller.) When the result of an operation falls outside this 
range, the exception OverflowError is raised. For the purpose of shift 
and mask operations, integers are assumed to have a binary, 2's 
complement notation using 32 or more bits, and hiding no bits from the 
user (i.e., all 4294967296 different bit patterns correspond to 
different values).
</quote>

To recap:

On systems where the supported range does not include -BIGNEG:
[i.e all systems unless the Tim has ported Python to a ones-complement 
machine in his attic]

BIGNEG / (-1) must raise OverflowError. divmod(BIGNEG, -1) must raise 
OverflowError because it cannot return a correct value for the "div" 
part. We need to decide whether BIGNEG % (-1) should return the correct 
result (zero) or raise OverflowError or do whichever an implementor 
decides is most convenient, and document the decision. I vote for 
OverflowError, on pragmatic grounds.

Lapsing back ever so slightly into pedantry, I'd suggest also changing 
the doco to say "would fall outside" instead of "falls outside".

Cheers,
John