Adding a positive number and a negative number

John Machin sjmachin at lexicon.net
Sat Jan 31 03:41:45 CET 2009


On Jan 31, 4:10 am, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
> Grant Edwards wrote:
> > On 2009-01-30, MRAB <goo... at mrabarnett.plus.com> wrote:
> >> Eric Kang wrote:
> >>> In two's complement representation, can adding one positive
> >>> and one negative give you overflow?
> >> No.
> > AFAIK, in Python adding integers never gives you overlow
> > regardless of sign.
>
> Right, but he wants his homework answer.

For extra brownie points, here's a simple proof of the more general
proposition that adding a non-negative integer p and a non-positive
integer n can't overflow whatever the representation.

Let a be the most negative integer and b the most positive. So we're
given a <= n <= 0 <= p <= b and need to show that a <= (p + n) <= b.

max(p) is b, max(n) is 0, so max(p + n) is b.
Similarly min(p + n) is a.
Q.E.D.

IEEE 754 floating point? I don't know. Go read the standard :-)




More information about the Python-list mailing list