sjmachin at lexicon.net
Thu Aug 21 00:32:23 CEST 2008
On Aug 21, 7:46 am, Fredrik Lundh <fred... at pythonware.com> 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 on built-in function cmp in module __builtin__:
cmp(x, y) -> integer
Return negative if x<y, zero if x==y, positive if x>y.
>>> cmp(10, 90)
Perhaps safer and better documentation to define your own sign and
sign = lambda x: x < 0
sign = lambda x: -1 if x < 0 else 0 if x == 0 else 1
samesign = lambda a, b: sign(a) == sign(b)
More information about the Python-list