Negative integers

Derek Martin code at
Thu Aug 21 01:21:23 CEST 2008

On Wed, Aug 20, 2008 at 02:38:11PM -0700, johnewing wrote:
> I am trying to figure out how to test if two numbers are of the same
> sign (both positive or both negative).  I have tried
> abs(x) / x == abs(y) / y

Zero is a problem, no matter how you slice it.  Zero can be considered
positive or negative (mathematically, 0 = -0).

If you want zero to be treated always as positive, you can write this:

def same_sign(a, b):
    return (abs(a) == a) == (abs(b) == b)

If you want to respect zero's duplicitous nature, you have to write it
like this:

def same_sign(a, b):
    if a == 0 or b == 0:
        return True
    return (abs(a) == a) == (abs(b) == b)

The first version *almost* works for the duplicitous zero:
>>> sign(-0, 1)
>>> sign(0, 1)
>>> sign(0, -1)

Close, but no cigar.

Derek D. Martin
GPG Key ID: 0x81CFE75D

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list