Skip to content
scipython.com

P2.2.3The sign function

Some languages provide a sign(a) function which returns -1 if its argument, a, is negative and 1 otherwise. Python does not provide such a function, but the math module does include a function math.copysign(x, y) which returns the absolute value of x with the sign of y. How would you use this function in the same way as the missing sign(a) function?

Show solution

Simply call math.copysign() with 1 as its first argument, casting to int if required:

>>> math.copysign(1, -4)
-1.0
>>> int(math.copysign(1, 5))
1