Reputation: 1088
I have a variable of type int, it's Python, so it can be positive and negative. Now, I want to make another variable have the same sign as the first variable1. It's easy to do this by using an if statement and then assign -1 or +1 to a variable and multiply every variable I want to have this sign by the -1 or +1. But then I thought maybe there is another way to do this (e.g. a built-in function). Is there something like "sign = getsignbit(value)"?
edit: Solved! math.copysign did the thing, cmp(x,0) works too, but I don't only want -1, 0 or 1, but also turn a 5 into -5.
Upvotes: 0
Views: 1030
Reputation: 16007
I don't think there is a built-in function, but you can roll your own easily enough:
def the_sign(num):
return cmp(num, 0)
Upvotes: 3
Reputation: 37344
There's no built in sign
function (see this answer for some explanation: Why doesn't Python have a sign function? ), but math.copysign
might be useful to you.
http://docs.python.org/2/library/math.html#math.copysign
Upvotes: 3