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

Published: October 08, 2021

Updated: December 09, 2022

Tags: Python; Math;

DMCA.com Protection Status

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