How to get the sign of a number (e.g -1 or +1) in python ?

Active October 08, 2021    /    Viewed 594    /    Comments 0    /    Edit


Examples of how to get the sign of a number (e.g -1 or +1) in python:

Get the sign of a number in python

Let's consider the following variables in python:

x1 = 42

x2 = -24

To get the sign of those numbers a solution is to use the function copysign(x, y) from python's math module:

import math

math.copysign(1,x1)

will returns:

1

while

math.copysign(1,x2)

will returns:

-1

copysign(a,b) gives the sign of b and the absolute value of a, So for example:

math.copysign(-4,2)

gives

4

Create a sign function from math.copysign(1, x)

Create a function sign

sign = lambda x: math.copysign(1, x)

then

x = 42

sign(x)

gives

1

Another example

x = -24

sign(x)

gives

-1

Create your own function

Another example, try to create your own function

def mysign(x):
    if x >= 0: 
        return 1
    else:
        return -1

Then

x = 42
print( mysign(x) )

gives

1

while

x = -24
print( mysign(x) )

gives

-1

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!