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) True >>> sign(0, 1) True >>> sign(0, -1) False Close, but no cigar. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D
pgpQtTAL0kmlA.pgp
Description: PGP signature
-- http://mail.python.org/mailman/listinfo/python-list