In Python, there is no sign function, but it is easy to get the sign of a number by defining our own sign function.
def sign_function(x):
if x > 0:
return 1
elif x == 0:
return 0
else:
return -1
print(sign_function(-10))
# Output:
-1
You can also use the Math module copysign() function – the second parameter is the number which you want to check the sign.
print(math.copysign(1, -3))
# Output:
-1
The numpy module also has a sign function you can use to get the sign of numbers in an array.
import numpy as np
print(np.sign([10,0,-10])
# Output:
[1, 0, -1]
In mathematics and computer science, the sign function is simple yet very common and useful for many applications.
By definition, the sign function is a function where numbers greater than 0 are assigned a value of 1, numbers equal to 0 are assigned a value of 0, and numbers less than 1 are assigned a value of -1.
When working in Python, it may be useful to be able to easily find the sign of numbers.
Unfortunately, there is not a built-in sign function, but we can easily define one ourselves.
Below is an example of how you can create your own sign function in Python.
def sign_function(x):
if x > 0:
return 1
elif x == 0:
return 0
else:
return -1
print(sign_function(10))
print(sign_function(-10))
# Output:
1
-1
How to Find the Sign of a Number in Python with the Math Module
If you don’t want to define your own sign function, you can use a function from the math module.
While the math module doesn’t have a sign function, the copysign() function from the math module can return the sign of a number.
The copysign() function takes two inputs. The idea with copysign() is it returns the first input with the sign of the second input.
So if all you want is the sign of a number, you can pass ‘1’ for the first input and your number for the second input.
Below is a simple example showing how to use the math module copysign() function in Python.
print(math.copysign(1, -3))
print(math.copysign(1, 5))
# Output:
-1
1
Using the numpy Module Sign Function to Find the Signs of Numbers in an Array
The numpy module also has a sign function.
You can use the numpy module sign function to find the sign of numbers in an array. Just pass an array of numbers and you will get back an array of their signs.
Below is an example of how you can find the signs of numbers in an array in Python with numpy.
import numpy as np
print(np.sign([10,0,-10])
# Output:
[1, 0, -1]
Hopefully this article has been useful for you to learn how to create a Python sign function and find the sign of numbers in Python.