On Aug 21, 7:46 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> 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
>
> > but that fails when one of the numbers is 0.  I'm sure that there is
> > an easy way to do this.  Any suggestions?
>
> (a < 0) == (b < 0)
>

That supposes that the OP understands "sign" to mean "the sign bit".
Another possibility is the sgn/sign/signum function (http://
en.wikipedia.org/wiki/Sign_function). In that case the answer would be
cmp(a, 0) == cmp(b, 0) -- with one big caveat:

Although cmp appears to return only -1, 0, or +1, it is documented to
return "negative", "zero" or "positive".

>>> help(cmp)
Help on built-in function cmp in module __builtin__:

cmp(...)
    cmp(x, y) -> integer

    Return negative if x<y, zero if x==y, positive if x>y.

>>> cmp(10, 90)
-1

Perhaps safer and better documentation to define your own sign and
samesign:

sign = lambda x: x < 0
or
sign = lambda x: -1 if x < 0 else 0 if x == 0 else 1
samesign = lambda a, b: sign(a) == sign(b)

Cheers,
John
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to